From: Robert Klemme Date: 2008-05-09T00:17:08+09:00 Subject: Re: idiom for Hash like map... 2008/5/8 Mikel Lindsaar : > On Thu, May 8, 2008 at 12:51 AM, ara.t.howard wrote: >> On May 7, 2008, at 5:18 AM, Mikel Lindsaar wrote: >> class Fruit >> def to_hash >> { :name => name, :price => price } >> end >> end >> array.each{|fruit| hash.update fruit.to_hash} > > Hmm.. put the responsibility back into the class. I guess that > actually makes the most sense. But this approach has the drawback to create a lot of temporary instances that are thrown away immediately. Of course I do not know your use case but if I was building an index I'd rather insert the object as value instead of a field. Just for the fun of it: irb(main):001:0> Fruit = Struct.new :name, :price => Fruit irb(main):002:0> fruits = [Fruit.new("foo",1),Fruit.new("bar",2)] => [#, #] irb(main):005:0> indexes = Hash.new {|h,k| h[k]= Hash.new(&h.default_proc)} => {} irb(main):006:0> fruits.each {|f| f.members.each {|m| indexes[m][f[m]]=f}} => [#, #] irb(main):008:0> require 'pp' => true irb(main):009:0> pp indexes {"name"=> {"foo"=>#, "bar"=>#}, "price"=> {1=>#, 2=>#}} => nil Cheers robert -- use.inject do |as, often| as.you_can - without end