使用哈希键来引用现有数组

时间:2013-08-20 18:44:38

标签: ruby

如果我有以下数组:

alice = ["phone", "telegraph"]
bob   = ["paper", "book" ]
carol = ["photograph", "painting"]

和这个哈希:

test_hash = { "alice" => "employee 1", "bob" => "employee 2", "carol" => "employee 3" }

我将如何遍历哈希并使用键值引用回数组,以便我可以提取,例如,alice拥有手机的事实?

2 个答案:

答案 0 :(得分:2)

首先需要哈希:

hsh = {"alice" => ["phone", "telegraph"],
       "bob"   => ["paper", "book" ],
       "carol" => ["photograph", "painting"]}

test_hash = { "alice" => "employee 1", "bob" => "employee 2", "carol" => "employee 3" }

test_hash.each{|k,v| puts v if hsh.has_key?(k)}
# >> employee 1
# >> employee 2
# >> employee 3

,或者

test_hash.each{|k,v| puts hsh[k] if hsh.has_key?(k)}
# >> phone
# >> telegraph
# >> paper
# >> book
# >> photograph
# >> painting

答案 1 :(得分:1)

不推荐,但可行:

alice = ["phone", "telegraph"]
bob   = ["paper", "book" ]
carol = ["photograph", "painting"]

test_hash = { "alice" => "employee 1", "bob" => "employee 2", "carol" => "employee 3" }

test_hash.keys.each {|k| puts "#{k} has phone." if eval(k).include? 'phone'}