From: Christopher Swasey Date: 2008-02-20T10:51:19+09:00 Subject: Re: IP Address to Decimal - is an one-liner possible? On 2/19/08, Tiago Pinto wrote: > 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? Use #inject, and instead of indexes rely on the size of the memo array: "127.0.0.1".split(".").map { |i| i.to_i }.reverse.inject([]) { |memo, part| memo << part * (256 ** memo.size) }.inject(0) { |memo, part| memo += part } Christopher