如何使用rails中的helper方法迭代包含深层嵌套数组的哈希

时间:2014-12-01 20:27:14

标签: ruby-on-rails ruby

我有一个带有深嵌套数组的哈希。我需要迭代它并找到56H的值,例如,并拉出其相关的人类可读名称Manager。在rails中使用辅助方法,我该怎么做?这是哈希表:

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']]
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

在不理解结构或上下文的情况下,我最好的答案是迭代哈希中的每个元素,然后遍历哈希值中的每个数组。我不确定你的意思是什么"人类可读的名字"因为两个散列键和第一个数组元素是人类可读的名称。我假设你的意思是我的代码中的哈希键,但这可能不正确。

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

答案 1 :(得分:2)

如果要查找多个地址,可以执行以下操作:

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"

构造哈希的另外两种方法:

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

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

如果同一个“密钥”(例如"Employee")同时包含HASH_TABLE['Users']HASH_TABLE['Visitor'],则可能更有用:

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"]