From: Sean O'Halpin Date: 2009-02-02T02:31:45+09:00 Subject: Re: Array#to_h On Sat, Jan 31, 2009 at 7:49 PM, Roger Pack wrote: > Not that I would find it useful at all, but is there is a Hash#to_a > should there not be an Array#to_h? > Thanks! > -=r It's useful in Ruby 1.8.x for those enumerable methods which return arrays, e..g irb --> {:a => 1, :b => 2, :c => 3}.select{|k, v| v % 2 == 1 } ==> [[:c, 3], [:a, 1]] irb --> {:a => 1, :b => 2, :c => 3}.select{|k, v| v % 2 == 1 }.to_hash ==> {:a=>1, :c=>3} whereas in Ruby 1.9.x, select (map, etc.) return hashes: irb(main):001:0> {:a => 1, :b => 2, :c => 3}.select{|k, v| v % 2 == 1 } => {:a=>1, :c=>3} The problem is, as other posters have noted, that there is no 1-1 mapping between an array and a hash. Having said that, I've found the following to be handy (mainly in restoring a hash after the 1.8.x transformation to an array): module ToHash if RUBY_VERSION =~ /^1.9/ def to_hash Hash[*flatten(1)] end else def to_hash Hash[*(inject([]) {|arr, i| i.kind_of?(Array) ? arr.push(*i) : arr.push(i) })] end end end used like this: b = [ [:a, [[1, 2], [3, 4]]], [:b, 3], [:c, { :d => 4 }], ] p b.extend(ToHash).to_hash Regards, Sean