Tampa
Tampa

Reputation: 78324

in ruby how to remove the last part of ip address

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

Answers (7)

Enver Dzhaparoff
Enver Dzhaparoff

Reputation: 4421

Simplest way, in my opinion:

"208.68.38.12"[/(\.?\d+){3}/]

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230461

Yet another version:

ip = "208.68.38.12"
ip[0...ip.rindex('.')] # => "208.68.38"

Upvotes: 3

Aleksei Matiushkin
Aleksei Matiushkin

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

Yam Marcovic
Yam Marcovic

Reputation: 8141

ip = ip.split('.')[0..-2].join('.')

Upvotes: 0

undur_gongor
undur_gongor

Reputation: 15954

Assuming you can rely on a well-formed IPv4 address:

ip.sub(/\.[^.]*\z/, '')

Upvotes: 0

Vasfed
Vasfed

Reputation: 18474

Try:

"208.68.38.12".split('.')[0,3].join('.') #=> "208.68.38"

Upvotes: 1

shivam
shivam

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

Related Questions