问题
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