From: Rob Biedenharn Date: 2008-05-07T20:54:21+09:00 Subject: Re: idiom for Hash like map... On May 7, 2008, at 7:18 AM, Mikel Lindsaar wrote: > class Fruit > attr_accessor :name, :price > def initialize(args) > @name = args[:name] > @price = args[:price] > end > end > > array = [ Fruit.new(:name => "apple", :price => 2), > Fruit.new(:name => "grape", :price => 20), > Fruit.new(:name => "pear", :price => 200) ] > > hash = Hash.new > > array.each do |obj| > hash.merge!({obj.name => obj.price}) > end > > hash.inspect # => "{\"grape\"=>20, \"apple\"=>2, \"pear\"=>200}" > > > The "hash = {} / hash.merge!" thing bugs me... what is the better way? > > Mikel If your general question is something like, "How can I take an array of objects and turn it into a key/value hash where the key and the value are based on methods on each object?" Then you could do something like: irb> Hash[*array.map{|f|[f.name,f.price]}.flatten] => {"grape"=>20, "apple"=>2, "pear"=>200} If any of the attributes (methods) return Arrays, the flatten will not produce the result that you want. Also, if the 'name's aren't unique, the hash will have fewer pairs that the array had entries. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com