Mi sembra di correre in questo molto spesso. Ho bisogno di costruire un hash da un array utilizzando un attributo di ciascun oggetto nell'array come chiave.
Diciamo che ho bisogno di un hash di esempio utilizza objecs ActiveRecord digitato da loro ID modo comune:
ary = [collection of ActiveRecord objects]
hash = ary.inject({}) {|hash, obj| hash[obj.id] = obj }
Un altro modo:
ary = [collection of ActiveRecord objects]
hash = Hash[*(ary.map {|obj| [obj.id, obj]}).flatten]
Sogno Way: ho potuto e potrebbe creare questo me stesso, ma c'è qualcosa in Ruby o Rails che sarà questo?
ary = [collection of ActiveRecord objects]
hash = ary.to_hash &:id
#or at least
hash = ary.to_hash {|obj| obj.id}