【发布时间】:2010-09-29 14:12:20
【问题描述】:
我似乎经常遇到这种情况。我需要使用数组中每个对象的属性作为键,从数组中构建一个哈希。
假设我需要一个示例使用 ActiveRecord 对象的哈希,这些对象由它们的 id 键控 常用方式:
ary = [collection of ActiveRecord objects]
hash = ary.inject({}) {|hash, obj| hash[obj.id] = obj }
另一种方式:
ary = [collection of ActiveRecord objects]
hash = Hash[*(ary.map {|obj| [obj.id, obj]}).flatten]
梦想之路: 我可以并且可能自己创建它,但是 Ruby 或 Rails 中是否有任何东西可以做到这一点?
ary = [collection of ActiveRecord objects]
hash = ary.to_hash &:id
#or at least
hash = ary.to_hash {|obj| obj.id}
【问题讨论】:
标签: ruby-on-rails ruby arrays hash