From: Gregory Seidman Date: 2008-02-20T10:55:45+09:00 Subject: Re: IP Address to Decimal - is an one-liner possible? On Wed, Feb 20, 2008 at 10:38:36AM +0900, Tiago Pinto wrote: > 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, 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. ip_s.split('.').inject(0) { |t,v| v.to_i + t*256 } > Best, > Tiago --Greg