Ruby编程:如何截断IP地址? [英] Ruby programming: How to truncate IP address?

查看:163
本文介绍了Ruby编程:如何截断IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于各种目的,我发现自己需要截断IP地址,我需要通过更改末尾."之后的最后一个数字来将程序中的IP地址从(xx.x.x.x)更改为(xx.x.x.1).字符串中的值为1.

For various purposes I find myself needing to truncate an IP address, I need to alter an IP address within my program from (xx.x.x.x) to (xx.x.x.1) by changing the last number after the final "." in the string to the value of 1.

我的理论是,可以通过将字符串从最末端截断到最后的.",并在其末尾添加"1"来实现,也可以通过命令程序更改字符串值来实现最后一个."之后等于1-我都不知道该怎么做.

I theorise that this could be achieved by either truncating the string from the very end up to the final ".", and adding a "1" onto the end of it, or somehow by ordering the program to alter the string value after the final "." to be equal to 1 - none of which i know how to do.

我已经看过各种关于在Ruby中截断和更改字符串的教程,但是似乎没有一个教程涵盖如此复杂的内容.

I have seen various tutorials on both truncating and altering strings in Ruby, however none seem to cover something quite as complicated.

简而言之,我的问题:

-如何更改最后一个"之后的最后一个数字的值.我的IP地址中的值是否为1(使用上述第2段中的任何一种方法)?

-这是否需要将变量类从字符串更改为int等?

谢谢.

推荐答案

Ruby是一种面向对象的语言,而不是面向字符串或面向整数的语言.您应该在程序中使用对象,而不是字符串或整数. (当然,除非您的对象 是字符串或整数.但是IP地址不是字符串或整数,而是IP地址.)

Ruby is an object-oriented language, not a string-oriented or integer-oriented language. You should use objects in your program, not strings or integers. (Unless your objects are strings or integers, of course. But an IP address is not a string or an integer, it's an IP address.)

一旦切换到使用IP地址,您的问题就变得微不足道了:

Once you switch over to using IP addresses, your problem becomes trivial:

require 'ipaddr'

ip = IPAddr.new('12.34.56.78')

(ip & IPAddr.new(255.255.255.0)).succ
# => #<IPAddr: IPv4:12.34.56.1/255.255.255.255>

这篇关于Ruby编程:如何截断IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆