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
最短的一个?
# 'Region' is a sample class here # you can put 'self.to_hash' method into any class you like class Region < ActiveRecord::Base def self.to_hash Hash[*all.map{ |x| [x.id, x] }.flatten] end end
如果有人得到普通阵列
arr = ["banana", "apple"] Hash[arr.map.with_index.to_a] => {"banana"=>0, "apple"=>1}
您可以自己将to_hash添加到Array.
class Array def to_hash(&block) Hash[*self.map {|e| [block.call(e), e] }.flatten] end end ary = [collection of ActiveRecord objects] ary.to_hash do |element| element.id end