krystah
krystah

Reputation: 3733

Select a portion of an IP

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

Answers (2)

falsetru
falsetru

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

Santhosh
Santhosh

Reputation: 29174

str[/(\d+\.){3}/]
# => "10.0.0." 

Upvotes: 3

Related Questions