0

if I have the following arrays:

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

and this hash:

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

how would I iterate through the hash and use the key value to refer back to the array so that I can pull, for example, the fact that alice has the phone?

4

2 回答 2

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
于 2013-08-20T18:48:00.163 回答
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'}
于 2013-08-20T19:07:54.440 回答