首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >按特定要求对散列数组进行Ruby排序

按特定要求对散列数组进行Ruby排序
EN

Stack Overflow用户
提问于 2021-01-27 16:09:00
回答 1查看 51关注 0票数 0

我需要对散列数组进行排序:

代码语言:javascript
复制
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

代码语言:javascript
复制
  def match_invoice_number(resource)
    bank_transfer.purpose&.include?(resource['description'])
  end

second - match_amount

代码语言:javascript
复制
  def match_amount(resource)
    bank_transfer.amount_cents == resource['total_gross_amount'] || resource['gross_amount_cents']
  end

third - match_vendor

代码语言:javascript
复制
  def match_vendor(resource)
    resource['contractor'].include?(bank_transfer.creditor_name)
  end

所以最后的资源应该是这样的:

代码语言:javascript
复制
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,但最终资源看起来与开始时一样。下面是我使用的内容:

代码语言:javascript
复制
  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
EN

Stack Overflow用户

发布于 2021-01-27 16:43:09

collection(resource)方法返回一个数组,当select检查它时,该数组被视为true值,因此您可以获得整个集合。要进行排序,可以使用sort_by方法。如果您需要提升满足所有条件的物品,请使用all?方法:

代码语言:javascript
复制
resource.sort_by do |resource|
  collection(resource).all? ? 0 : 1 # To return sortable value
end

如果条件具有不同的优先级:

代码语言:javascript
复制
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
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65915128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档