From: Chiyuan Zhang Date: 2008-02-20T10:57:21+09:00 Subject: Re: IP Address to Decimal - is an one-liner possible? addr.split(".").zip([256**3,256**2,256,1]).inject(0) { |sum, a| sum + a[0].to_i*a[1] } :) and this (less efficient): eval(addr.split(".").inject("0") { |exp, num| "(#{exp})*256+#{num}" }) 2008/2/20, 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, 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: tpinto@webreakstuff.com > Company: http://webreakstuff.com/ > Personal blog: http://whythehype.com/ > >