Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

string - Ruby programming: How to truncate IP address?

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...