下面是要在哈希中搜索的示例哈希和示例数组:
nicknames = { "Black Mamba" => "Kobe Bryant",
"Half Man Half Amazing" => "Vince Carter",
"The Big Fundamental" => "Tim Duncan",
"Big Ticket" => "Kevin Garnett",
"Obi-Wan Ginobili" => "Manu Ginobili",
"The Answer" => "Allen Iverson" }
names = [ "Vince Carter", "Manu Ginobili", "Allen Iverson" ]
我想回来:
selected = { "Half Man Half Amazing" => "Vince Carter", "Obi-Wan Ginobili" => "Manu Ginobili", "The Answer" = "Allen Iverson" }
做这个有什么好方法谢谢!
最佳答案
您只需执行以下操作:
nicknames.select { |key, value| names.include?(value) }
(复制粘贴你提供的代码和我的代码在你的irb控制台,你会看到它工作)。