T
Tiago Pinto
Hi guys,
A friend of mine needs to convert a string containing an IP Address
(such as "127.0.0.1") to a decimal (that example would translate to
2130706433, <http://www.allredroster.com/iptodec.htm> said).
We got a solution (that can easily be written in 2 lines):
ip_d = 0 # let's start with zero
ip_s = "127.0.0.1" # this our ip address as a string
ip_a = ip_s.split(".") # now it's an array
ip_i = ip_a.map{|i| i.to_i} # an array of ints
ip_i.reverse! # let's reverse so we can use the array's indexes as the
exponents when translating from base 256 to base 10)
ip_i.each_with_index{|e,i| ip_d += e*(256**i)} # this is pure math,
we're just changing bases here
Our challenge (between me and my friend) was getting an one-liner for
this. I think it'd be easy with something like Array#map_with_index or
Array#inject_with_index because we use the indexes, here.
What do you think? There's a way to do this? Is this just a silly question?
I know, we should be working, but we both love Ruby.
Best,
Tiago
--
Tiago Pinto
Partner, Developer and Event Coordinator - Webreakstuff
Email: (e-mail address removed)
Company: http://webreakstuff.com/
Personal blog: http://whythehype.com/
A friend of mine needs to convert a string containing an IP Address
(such as "127.0.0.1") to a decimal (that example would translate to
2130706433, <http://www.allredroster.com/iptodec.htm> said).
We got a solution (that can easily be written in 2 lines):
ip_d = 0 # let's start with zero
ip_s = "127.0.0.1" # this our ip address as a string
ip_a = ip_s.split(".") # now it's an array
ip_i = ip_a.map{|i| i.to_i} # an array of ints
ip_i.reverse! # let's reverse so we can use the array's indexes as the
exponents when translating from base 256 to base 10)
ip_i.each_with_index{|e,i| ip_d += e*(256**i)} # this is pure math,
we're just changing bases here
Our challenge (between me and my friend) was getting an one-liner for
this. I think it'd be easy with something like Array#map_with_index or
Array#inject_with_index because we use the indexes, here.
What do you think? There's a way to do this? Is this just a silly question?
I know, we should be working, but we both love Ruby.
Best,
Tiago
--
Tiago Pinto
Partner, Developer and Event Coordinator - Webreakstuff
Email: (e-mail address removed)
Company: http://webreakstuff.com/
Personal blog: http://whythehype.com/