Reputation: 78324
I am new to ruby.
I have an ip address and I need the strip the last part of the ip address.
e.g.
208.68.38.12 becomes 208.68.38
How do I do that in ruby?
Upvotes: 2
Views: 1492
Reputation: 4421
Simplest way, in my opinion:
"208.68.38.12"[/(\.?\d+){3}/]
Upvotes: 0
Reputation: 230461
Yet another version:
ip = "208.68.38.12"
ip[0...ip.rindex('.')] # => "208.68.38"
Upvotes: 3
Reputation: 121000
ip = '208.68.38.12'
ip[/.*(?=\.\d+\z)/]
#⇒ "208.68.38"
Here we use String#[]
and positive lookahead in regular expression to omit last dot and following numbers in the result.
BTW, there are gems all around to deal with IPs, e. g.: https://github.com/deploy2/ruby-ip
Upvotes: 1
Reputation: 15954
Assuming you can rely on a well-formed IPv4 address:
ip.sub(/\.[^.]*\z/, '')
Upvotes: 0
Reputation: 16506
Can be done this way:
ip = "208.68.38.12"
ip.split(".")[0...-1].join(".")
#=> "208.68.38"
If you go step by step, the above used line of code is quite self-explanatory. Here:
ip.split(".") # splitting string on `.` so we have an Array
#=> ["208", "68", "38", "12"]
ip.split(".")[0...-1] # taking 0th to n-1 th element of Array (-1 represents last element when size is unknown)
#=> ["208", "68", "38"]
ip.split(".")[0...-1].join(".") # finally joining the Array over `.`
#=> "208.68.38"
Upvotes: 5