我似乎经常遇到这种情况。我需要使用数组中每个对象的属性作为键从数组构建哈希。
比方说我需要一个散列的例子使用 ActiveRecord objecs 通过他们的 ids 键控 常用方式:
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}
最佳答案
ActiveSupport 中已经有一个方法可以做到这一点。
['an array', 'of active record', 'objects'].index_by(&:id)
作为记录,这里是实现:
def index_by
inject({}) do |accum, elem|
accum[yield(elem)] = elem
accum
end
end
可以重构为(如果您急需单行代码):
def index_by
inject({}) {|hash, elem| hash.merge!(yield(elem) => elem) }
end
关于ruby-on-rails - 从数组创建哈希的最简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/412771/