通过与数组比较来选择散列元素

Selecting hash elements by comparing with array

我正在寻找 Ruby/Rails 方法来处理经典 "select items from a set based on matches with another set" 任务。

第一个是一个简单的散列,像这样:

  fruits = {:apples => "red", :oranges => "orange", :mangoes => "yellow", :limes => "green"}

设置二是一个数组,像这样:

   breakfast_fruits = [:apples, :oranges]

期望的结果是包含 Breakfast_fruits:

中列出的水果的散列
    menu = {:apples => "red", :oranges => "orange"}

我有一个基本的嵌套循环,但我坚持使用基本的比较语法:

   menu = {}

   breakfast_fruits.each do |brekky|
      fruits.each do |fruit|
         //if fruit has the same key as brekky put it in menu
      end
   end

我也很想知道在 Ruby 中是否有比嵌套迭代器更好的方法。

您可以使用 Hash#keep_if:

fruits.keep_if { |key| breakfast_fruits.include? key }
# => {:apples=>"red", :oranges=>"orange"}

这将修改 fruits 本身。如果您不希望这样,可以对您的代码稍作修改:

menu = {}
breakfast_fruits.each do |brekky|
    menu[brekky] = fruits[brekky] if breakfast_fruits.include? brekky
end

ActiveSupport(随 Rails 提供)添加 Hash#slice:

slice(*keys)

Slice a hash to include only the given keys. Returns a hash containing the given keys.

所以你可以这样说:

h = { :a => 'a', :b => 'b', :c => 'c' }.slice(:a, :c, :d)
# { :a => 'a', :c => 'c' }

在你的例子中,你会展开数组:

menu = fruits.slice(*breakfast_fruits)