我需要对散列数组进行排序:
resource = [{ 'resource_id' => 34,
'description' => 'NR00123',
'total_gross_amount_cents' => bank_transfer.amount_cents,
'contractor_name' => 'Bogisich Inc' },
{ 'resource_id' => 35,
'description' => bank_transfer.purpose,
'total_gross_amount_cents' => 54321,
'contractor' => 'Bogisich Inc' },
{ 'resource_id' => 36,
'description' => 'Some description 2',
'total_gross_amount_cents' => 0123,
'contractor' => bank_transfer.creditor_name
}
]通过以下要求:
first - match_invoice_number
def match_invoice_number(resource)
bank_transfer.purpose&.include?(resource['description'])
endsecond - match_amount
def match_amount(resource)
bank_transfer.amount_cents == resource['total_gross_amount'] || resource['gross_amount_cents']
endthird - match_vendor
def match_vendor(resource)
resource['contractor'].include?(bank_transfer.creditor_name)
end所以最后的资源应该是这样的:
resource = [
{ 'resource_id' => 35,
'description' => bank_transfer.purpose,
'total_gross_amount_cents' => 54_321,
'contractor' => 'Bogisich Inc' },
{ 'resource_id' => 34,
'description' => 'NR00123',
'total_gross_amount_cents' => bank_transfer.amount_cents,
'contractor_name' => 'Bogisich Inc' },
{ 'resource_id' => 36,
'description' => 'Some description 2',
'total_gross_amount_cents' => 0o123,
'contractor' => bank_transfer.creditor_name }
]我尝试使用select,但最终资源看起来与开始时一样。下面是我使用的内容:
def only_suggested(resource)
resource.select do |resource|
collection(resource)
end
end
def collection(resource)
[match_invoice_number(resource), match_amount(resource), match_vendor(resource)]
end发布于 2021-01-27 16:43:09
collection(resource)方法返回一个数组,当select检查它时,该数组被视为true值,因此您可以获得整个集合。要进行排序,可以使用sort_by方法。如果您需要提升满足所有条件的物品,请使用all?方法:
resource.sort_by do |resource|
collection(resource).all? ? 0 : 1 # To return sortable value
end如果条件具有不同的优先级:
resource.sort_by do |resource|
if match_invoice_number(resource)
0
elsif match_amount(resource)
1
elsif match_vendor(resource)
2
else
3
end
endhttps://stackoverflow.com/questions/65915128
复制相似问题