Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...