Skip to content

Instantly share code, notes, and snippets.

@whylom
Last active December 25, 2015 20:19
Show Gist options
  • Save whylom/7034575 to your computer and use it in GitHub Desktop.
Save whylom/7034575 to your computer and use it in GitHub Desktop.
Array#to_hash converts an array of instances into a hash using the provided pair of methods to determine the key & value of each row
# example class
class State < Struct.new(:name, :code)
def self.all
[
State.new('Alabama', 'AL'),
State.new('Alaska', 'AK'),
State.new('Arizona', 'AZ')
]
end
end
# the magical Array#to_hash extension
class Array
def to_hash(hash)
key, value = hash.first
self.reduce({}) do |hash, member|
hash.merge(member.send(key) => member.send(value))
end
end
end
State.all.to_hash(:code => :name)
#=> { 'AL' => 'Alabama', 'AK' => 'Alaska', 'AZ' => 'Arizona' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment