2013-08-20 39 views
0

如果我有以下的數組:使用散列密鑰來指代現有陣列

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

和該散列:

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

我如何將通過散列迭代,並使用該密鑰值回到陣列,以便我可以拉動,例如,愛麗絲手機的事實?

+7

我強烈建議,以避免依賴變量'的名字。你可以創建另一個哈希值,比如'person1 = {alice => [「phone」,「something else」]}',然後將所有人收集到'persons'數組中並查詢該數組。再次,不要依賴變量命名。 – tkroman

+0

贊同@cdshines這個模式聞起來很糟糕。 – fguillen

+0

很好的建議。我會去做。 – AltGrendel

回答

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 
+0

謝謝,這是要走的路。這是一個「首先做對」的案例。 – AltGrendel

+0

@AltGrendel很好,你選擇了正確的方式,但你的問題是「我將如何遍歷散列並使用鍵值返回數組」,而不是「實現數據結構的最佳實踐」。 ;-p – jaeheung

+0

沒錯,我很欣賞你們兩個都給了我這個問題的實際答案,並建議我在引發問題之前保持最佳實踐。 – AltGrendel

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