Ruby 如何从数组中动态选择数据

Ruby 如何从数组中动态选择数据,ruby,ruby-on-rails-4,Ruby,Ruby On Rails 4,我有一个类似的数组 [ { id: 1, name: 'John', status: 'completed' }, { id: 2, name: 'Sam', status: 'pending' }, { id: 3, name: 'Joe', status: 'in process' }, { id: 4, name: 'Mak', status: 'completed' } ] 从阵列中动态选择数据的最佳方法是什么?e、 g如果我通过了,请说出id和状态 我试过这个 arra

我有一个类似的数组

[ { id: 1, name: 'John', status: 'completed' },
  { id: 2, name: 'Sam', status: 'pending' }, 
  { id: 3, name: 'Joe', status: 'in process' },
  { id: 4, name: 'Mak', status: 'completed' }
]
从阵列中动态选择数据的最佳方法是什么?e、 g如果我通过了,请说出id和状态

我试过这个

array.select {|a| a[:id] == 1 && a[:status] == 'completed' }
但用户可以只传递id或id和名称的组合。

这个怎么样

id = 1
status = 'completed'

array.select { |item| item[:id] == id && (status ? item[:status] == status : true) }
# => [{:id=>1, :name=>"John", :status=>"completed"}]

status = 'foo'
array.select { |item| item[:id] == id && (status ? item[:status] == status : true) }
# => []

status = nil
array.select { |item| item[:id] == id && (status ? item[:status] == status : true) }
# => [{:id=>1, :name=>"John", :status=>"completed"}]

只有当它不是
nil
时,它才会比较状态。通过
id
或同时通过
id
status
从数组中选择元素的一种方法是将
select
逻辑移动到一个方法中,并将其扩展到可选状态参数中,如下所示:

array = [ { id: 1, name: 'John', status: 'completed' },
          { id: 2, name: 'Sam', status: 'pending' }, 
          { id: 3, name: 'Joe', status: 'in process' },
          { id: 4, name: 'Mak', status: 'completed' }
        ]

def select_by(arr, id:, status: nil)
  arr.select do |hash|
    next unless hash[:id] == id
    next unless status && hash[:status] == status
    true
  end
end

select_by(array, id: 1)
# => [{:id=>1, :name=>"John", :status=>"completed"}]
select_by(array, id: 2, status: 'pending')
# => [{:id=>2, :name=>"Sam", :status=>"pending"}]
select_by(array, id: 3, status: 'not a real status')
# => []

希望这有帮助

谢谢。我试着做些改变,但没有结果。请检查此处的代码可能
def select\u by(*key\u value\u pairs)
?您已将此问题标记为
ruby-on-rails-4
。您真的有一个包含散列的普通数组吗?或者您实际上是在处理存储在数据库中的记录吗?如果是这样,您应该使用Rails,例如,
YourModel.find_by(id:1,status:'completed')