It seems I often came across this. I need to build a hash from an array using the attribute of each object in the array as a key.
Suppose I need an example hash, uses ActiveRecord objects bound by their identifiers. The usual way:
ary = [collection of ActiveRecord objects] hash = ary.inject({}) {|hash, obj| hash[obj.id] = obj }
Another way:
ary = [collection of ActiveRecord objects] hash = Hash[*(ary.map {|obj| [obj.id, obj]}).flatten]
Dream: I could and could create it myself, but is there anything in Ruby or Rails that it will be?
ary = [collection of ActiveRecord objects] hash = ary.to_hash &:id
arrays ruby ruby-on-rails hash
Daniel Beardsley Jan 05 '09 at 10:44 2009-01-05 10:44
source share