From: "David A. Black" Date: 2008-05-07T20:39:25+09:00 Subject: Re: idiom for Hash like map... Hi -- On Wed, 7 May 2008, 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? You might like this better: hash = Hash[*array.map {|e| [e.name, e.price] }.flatten ] or this: hash = array.inject({}) {|h, fruit| h[fruit.name] = fruit.price; h } David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!