Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traverse Nested Ruby Hash With Array of Keys

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
like image 608
Nicholas Erdenberger Avatar asked Jan 05 '23 01:01

Nicholas Erdenberger


2 Answers

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.

like image 154
Cary Swoveland Avatar answered Jan 14 '23 12:01

Cary Swoveland


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
like image 24
falsetru Avatar answered Jan 14 '23 12:01

falsetru