From: ara.t.howard@... Date: 2006-01-11T14:33:05+09:00 Subject: Re: Stupid question from a Ruby newb On Wed, 11 Jan 2006, Will wrote: > Hi folks, I know that this is a really simple question, and there must > be many ways to do it in Ruby... but what I'm looking for is an > elegant way to take a collection of objects and create a hash mapping > one attribute of the object as the key and the other as the value. So > far what I am doing is this: > > objects = some_method_to_return_collect( method_params ) > myHash = Hash.new > > @objects.each do |object| > myHash[ object.key ] = object.value > end > > I played around with doing something like: > > @myHash = objects.map do |object| [ object.key => object.value ] end > > But that returns an array of single-value hashes, which is not exactly > what I am trying to do. > > I know this is a stupid question, and probably pointless because I do > know ways to do it, but I would really like the know the Ruby Way to do > this. Ruby seems so given to elegant code that my code above really > bugs me for some reason. > > Thanks all! h = objects.inject({}){|h,o| h.update o.key => o.value} -a -- strong and healthy, who thinks of sickness until it strikes like lightning? preoccupied with the world, who thinks of death, until it arrives like thunder? -- milarepa