0

我正在使用 group_by 返回一个我想先按键排序的哈希,然后对该键下的值进行排序。

这是我到目前为止提出的代码。一切正常,除了我不知道如何在分组后对值进行排序。

我有一个方法,“pp_accounts_with_properties”,它显示了我的意图并以正确的顺序打印出所有内容(感谢properties.sort_by!调用)......但似乎我应该能够在“accounts_with_properties”中以某种方式完成这一点方法。

class ProofList
  attr_reader :client

  def initialize(client)
    @client = client
  end

  def properties
    @client.properties.joins(invoices: [charges: [:charge_credits]])
                      .where(charge_credits: { approved: false }).uniq
  end

  def accounts_with_properties
    unsorted_accounts_with_properties.sort_by { |account, properties| account[:acct_number] }
  end

  def unsorted_accounts_with_properties
    properties.group_by { |property| property.account }
  end

  def pp_accounts_with_properties
    accounts_with_properties.each do |account, properties|
      puts account.name
      properties.sort_by! { |p| p[:name] }
      properties.each do |property|
        puts property.name
      end
    end
  end

end
4

1 回答 1

1

你是...

  1. 谈论显示哈希的键和值的某种排序显示,或
  2. 实际上以某种方式重新排列 Hash 的内部结构?这样,例如,对 myhash.keys 的调用总是以特定顺序返回内容?

如果是2,为什么?你找错树了。散列只是键与值的关联,如果您正在做任何与键的顺序有关的事情(除了尝试制作漂亮/可读的显示),那么您将做错事。

查看这篇文章以获得比我更清晰的解释:http ://www.rubyinside.com/how-to/ruby-sort-hash

于 2013-09-26T21:56:08.327 回答