【问题标题】:Ruby search in Array of Hashes with multiple conditions [closed]具有多个条件的哈希数组中的 Ruby 搜索[关闭]
【发布时间】:2019-02-04 21:55:18
【问题描述】:

我正在尝试查询具有 2 个不同条件的哈希数组,但这不起作用:

array_list = [
  {type: 'sale', currency: 'CAD', price: '123'},
  {type: 'purchase', currency: 'CAD', price: '321'}
]

if array_list.select { |pt|
  pt[:type] == 'sale', pt[:currency] == 'CAD'
}.present?

end

有什么建议吗? 谢谢

【问题讨论】:

  • 你想要的是pt[:type] == 'sale' && pt[:currency] == 'CAD'
  • Ruby 中的赋值是单个 =。选择块中有一个意外的逗号。

标签: ruby-on-rails arrays ruby hash


【解决方案1】:

你还需要使用&&而不是使用Array#selectpresent?可以使用Array#any?

array_list = [
  {type: 'sale', currency: 'CAD', price: '123'},
  {type: 'purchase', currency: 'CAD', price: '321'}
]

if array_list.any? { |pt| pt[:type] == 'sale' && pt[:currency] == 'CAD'}
  # your logic
end

【讨论】:

    猜你喜欢
    • 2015-08-26
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2011-09-05
    • 2014-07-21
    相关资源
    最近更新 更多