Reputation: 3733
Say I have the IP address 10.0.0.47
How can I manipulate it cleverly so that I am left with 10.0.0.
?
chop
sprang to mind, but it's not dynamic enough. I want it to work regardless if the number after the last .
consists of 1 or 3 digits.
Upvotes: 2
Views: 45
Reputation: 369364
Using String#rindex
and String#[]
with range:
ip = "10.0.0.47"
ip[0..ip.rindex('.')] # from the first character to the last dot.
# => "10.0.0."
or using regular expression:
ip[/.*\./] # greedy match until the last dot
# => "10.0.0."
or using String#rpartition
and Array#join
:
ip.rpartition('.')[0,2].join
# => "10.0.0."
Upvotes: 4