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. 実際に何らかの方法でハッシュの内部構造を再配置していますか? たとえば、myhash.keys を呼び出すと、常に特定の順序で返されるようにするにはどうすればよいでしょうか?

2の場合、なぜですか?あなたは間違った木を吠えています。ハッシュはキーと値の単なる関連付けであり、キーの順序が重要な場合 (きれいで読みやすい表示を作成しようとする以外) は、間違った方法で何かを行っています。

私よりも明確な説明については、この記事をご覧ください: http://www.rubyinside.com/how-to/ruby-sort-hash

于 2013-09-26T21:56:08.327 に答える