【问题标题】:Selecting hash elements by comparing with array通过与数组比较选择哈希元素
【发布时间】:2015-01-31 01:51:20
【问题描述】:

我正在寻找 Ruby/Rails 方法来处理经典的“根据与另一组的匹配从一组中选择项目”任务。

Set one 是一个简单的哈希,像这样:

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

【问题讨论】:

  • 如果你只想要值,values_at 函数是要走的路。

标签: ruby-on-rails ruby arrays hash


【解决方案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

【讨论】:

【解决方案2】:

ActiveSupport(Rails 自带)添加了Hash#slice

切片(*keys)

对哈希进行切片以仅包含给定的键。返回包含给定键的哈希。

所以你可以这样说:

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

在你的情况下,你会 splat 数组:

menu = fruits.slice(*breakfast_fruits)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多