我发现我经常有遍历可枚举的方法,以便返回不同的可枚举或散列.这些方法几乎总是看起来像这个简单的例子: def build_hash(array) hash = {} array.each do |item| hash[ item[:id] ]= item end hash end 这种
def build_hash(array) hash = {} array.each do |item| hash[ item[:id] ]= item end hash end
这种方法有效,但我经常想知道是否有更简洁的方法来执行此操作,特别是无需将循环包装在临时对象中以便返回正确.
有没有人知道改进的和/或更清洁和/或更快的方法,或者这是最好的方式吗?
考虑到您的具体示例,以下是一些方法arr = [{:id => 1, :name => :foo}, {:id => 2, :name => :bar}] Hash[arr.map{ |o| [o[:id], o] }] arr.each_with_object({}){ |o, h| h[o[:id]] = o } arr.reduce({}){ |h, o| h[o[:id]] = o; h } arr.reduce({}){ |h, o| h.merge o[:id] => o } # each of these return the same Hash # {1=>{:id=>1, :name=>:foo}, 2=>{:id=>2, :name=>:bar}}