Given a hash with n levels of nested values, a field name, and a path
contact = {
"Email" => "[email protected]",
"Account" => {
"Exchange" => true,
"Gmail" => false,
"Team" => {
"Closing_Sales" => "Bob Troy",
"Record" => 1234
}
}
}
field = "Record"
path = ["Account", "Team"] #Must support arbitrary path length
How can one define a method that would retrieve the field value at the end of the path.
def get_value(hash, field, path)
?
end
get_value(contact, "Record", ["Account", "Team"])
=> 1234
Let's regard the "field" as the last element of the "path". Then it's simply
def grab_it(h, path)
h.dig(*path)
end
grab_it contact, ["Account", "Team", "Record"]
#=> 1234
grab_it contact, ["Account", "Team", "Rabbit"]
#=> nil
grab_it(contact, ["Account", "Team"]
# => {"Closing_Sales"=>"Bob Troy", "Record"=>1234}
grab_it contact, ["Account"]
#=> {"Exchange"=>true, "Gmail"=>false, "Team"=>{"Closing_Sales"=>"Bob Troy",
# "Record"=>1234}}
Hash#dig was added in v2.3.
You can use Array#inject
: to mean hash['Account']['Team']
then, return_value_of_inject['Record']
:
def get_value(hash, field, path)
path.inject(hash) { |hash, x| hash[x] }[field]
end
get_value(contact, field, path) # => 1234
BTW, how about get_value(contact, ['Account', 'Team', 'Record'])
?
def get_value2(hash, path)
path.inject(hash) { |hash, x| hash[x] }
end
get_value2(contact, ['Account', 'Team', 'Record']) # => 1234
or get_value(contact, 'Account.Team.Record')
def get_value3(hash, path)
path.split('.').inject(hash) { |hash, x| hash[x] }
end
get_value3(contact, 'Account.Team.Record') # => 1234
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With