簡體   English   中英

Ruby 按特定要求對哈希數組進行排序

[英]Ruby sort array of hashes by specific requirements

我需要對哈希數組進行排序:

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)方法返回一個數組,當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
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM