首页 > 解决方案 > 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

标签: ruby-on-railsruby

解决方案


collection(resource)方法返回一个数组,在检查它时将其视为trueselect,因此您可以取回整个集合。要排序,您可以使用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

推荐阅读