Tracing a nested Ruby Hash with an array of keys
Given a hash with n levels of nested values, the field name and path
contact = {
"Email" => "bob@bob.com",
"Account" => {
"Exchange" => true,
"Gmail" => false,
"Team" => {
"Closing_Sales" => "Bob Troy",
"Record" => 1234
}
}
}
field = "Record"
path = ["Account", "Team"] #Must support arbitrary path length
How to determine the method that will retrieve the value of the field at the end of the path.
def get_value(hash, field, path)
?
end
get_value(contact, "Record", ["Account", "Team"])
=> 1234
Consider the "field" as the last element of the "path". Then just
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 added in v2.3.
You can use Array#inject: to indicate 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
By the way, what 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