我有一个类似
的数组[ { 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' }
]
从数组中动态选择数据的最佳方法是什么?例如,如果我通过说id和状态
我试过这个
array.select {|a| a[:id] == 1 && a[:status] == 'completed' }
但是用户只能传递id或id和名称的组合。
答案 0 :(得分:1)
通过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')
# => []
希望这有帮助!
答案 1 :(得分:0)
这个怎么样
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
,它只会比较状态。