ruby-on-rails - Ruby 按特定要求对哈希数组进行排序
问题描述
我需要对哈希数组进行排序:
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
}
]
通过以下要求:
第一个 - match_invoice_number
def match_invoice_number(resource)
bank_transfer.purpose&.include?(resource['description'])
end
第二 - match_amount
def match_amount(resource)
bank_transfer.amount_cents == resource['total_gross_amount'] || resource['gross_amount_cents']
end
第三 - 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
解决方案
collection(resource)
方法返回一个数组,在检查它时将其视为true
值select
,因此您可以取回整个集合。要排序,您可以使用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
end
推荐阅读
- java - Java Spring 嵌套 bean
- python - Django Rest 框架:用户更新
- php - cookie 过期时间未设置为在每个浏览器关闭后销毁,但它不起作用
- python - Django:在此服务器上找不到请求的 URL /index.html
- python-3.x - 我正在尝试下载 kaggle 比赛 twosigma 的数据集
- twilio - 对 Twilio Flex Elements 的动态更改
- python - Kivy 自定义按钮文本
- javascript - 如何向 php 函数发送 ajax 请求,然后将函数的返回值发送回我的 ajax 函数响应?
- sql - 我想在 SQL 中按周设置下表组中的数据
- wpf - 如何在列表框中绑定元组列表?