Last active
December 25, 2015 20:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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