通过与数组比较来选择哈希元素

时间:2015-01-30 17:13:54

标签: ruby-on-rails ruby arrays hash

我正在寻找Ruby / Rails的方式来接近经典"根据与另一组的匹配来选择一组中的项目"任务。

Set one是一个简单的哈希,如下所示:

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

Set two是一个数组,如下所示:

   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中是否有比嵌套迭代器更好的方法。

2 个答案:

答案 0 :(得分:1)

您可以使用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

答案 1 :(得分:1)

ActiveSupport(随Rails一起提供)添加了Hash#slice

  

<强>片(*键)

     

将哈希切片以仅包含给定的键。返回包含给定键的哈希。

所以你可以这样说:

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

在你的情况下,你要摧毁阵列:

menu = fruits.slice(*breakfast_fruits)