Nicholas Alek
Nicholas Alek

Reputation: 273

How to iterate over a hash that contains deep nested array using helper method in rails

I have a hash with a deep nested array. I need to iterate over it and find the value of 56H, for example, and pull its related human readable name Manager. Using a helper method in rails, how can I do that? Here is the hash table:

HASH_TABLE = {
        'Users' => [['Manger','56H'],
                    ['Admin', '56A'],
                    ['Policy', '56B'],
                    ['Member','78C'],
                    ['Guest','764']],
      'Visitor' => [['Worker','55H'],
                    ['Employee','55A'],
                    ['Guest','55B'],
                    ['Temp Member','78C'],
                    ['NA','764AA']]
}

Thanks for any help!

Upvotes: 0

Views: 243

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110725

If you had more than one address to look up, you might do this:

HASH_TABLE.each_with_object({}) { |(_,v),h|
  v.each { |type, value| h[value] = type } }
  #=> {"56H"=>"Manager",     "56A"=>"Admin", "56B"=>"Policy",
  #    "78C"=>"Temp Member", "764"=>"Guest", "55H"=>"Worker",
  #    "55A"=>"Employee",    "55B"=>"Guest", "764AA"=>"NA"}

h["56H"] #=> "Manager"
h["55B"] #=> "Guest"

Two other ways of constructing the hash:

h = Hash[HASH_TABLE.values.flatten(1).map(&:reverse)]

and

h = Hash[HASH_TABLE.values.flatten(1)].invert

If the same "key" (e.g., "Employee") were in both HASH_TABLE['Users'] and HASH_TABLE['Visitor'], this might be more useful:

h = HASH_TABLE.each_with_object({}) { |(k,v),h|
  v.each { |type, value| h[value] = [k, type] } }
  # => {"56H"  =>["Users", "Manager"],    "56A"=>["Users", "Admin"],
  #     "56B"  =>["Users", "Policy"],     "78C"=>["Visitor", "Temp Member"],
  #     "764"  =>["Users", "Guest"],      "55H"=>["Visitor", "Worker"],
  #     "55A"  =>["Visitor", "Employee"], "55B"=>["Visitor", "Guest"],
  #     "764AA"=>["Visitor", "NA"]}

h["56H"] #=> ["Users",   "Manager"]
h["55B"] #=> ["Visitor", "Guest"]

Upvotes: 2

Matt Huggins
Matt Huggins

Reputation: 83299

Without understanding the structure or the context, my best answer is to iterate over each element in the hash, then each array in the hash value. I'm not sure here what you mean by "human readable name" since both the hash keys & the first array element is a human readable name. I assumed you meant the hash key in my code below, but this might not be correct.

def human_readable_name(str)
  HASH_TABLE.each do |key, array|
    array.each do |entry|
      return entry[0] if entry[1] == str
    end
  end
  nil
end

Upvotes: 2

Related Questions