Ruby programming: How to truncate IP address?

*爱你&永不变心* 提交于 2019-12-13 08:30:26

问题


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.

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.

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

In short, my question:

- How do i change the value of the last number after the final "." in my IP address to the value of 1 (using either aforementioned method in paragraph 2)?

- Will this require a variable class change from string to int etc?

Thank you in advance.


回答1:


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.)

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>


来源:https://stackoverflow.com/questions/33125711/ruby-programming-how-to-truncate-ip-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!