From: David Vallner Date: 2006-01-11T13:42:22+09:00 Subject: Re: Stupid question from a Ruby newb 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! > >-Will > > > > There are no stupid questions, only stupid people. The solution you first wrote where you're iterating over the array is as good as any, i would probably use that. If you like Ever So Cool one-liners, this one might also work: myHash = objects.inject({}){|hash, item| hash[item.key] = item.value; hash} It does pretty much completely the same, except were this Smalltalk, the block wouldn't be a closure and therefore a horse's butthair more memory-efficient solution. David Vallner