首页 > 解决方案 > 具有多个条件的哈希数组中的 Ruby 搜索

问题描述

我正在尝试查询具有 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

请问有什么建议吗?谢谢

标签: ruby-on-railsarraysrubyhash

解决方案


您还需要使用&&而不是使用Array#select并且present?可以使用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

推荐阅读