这是一个示例哈希和一个在哈希中搜索的示例数组:
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控制台中,您将看到它正常工作).