Cleanest way to create a Hash from an Array

There is already a method in ActiveSupport that does this.

['an array', 'of active record', 'objects'].index_by(&:id)

And just for the record, here’s the implementation:

def index_by
  inject({}) do |accum, elem|
    accum[yield(elem)] = elem
    accum
  end
end

Which could have been refactored into (if you’re desperate for one-liners):

def index_by
  inject({}) {|hash, elem| hash.merge!(yield(elem) => elem) }
end

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)