簡體   English   中英

按鍵值先后順序排序

[英]Order Ruby Hash by Key then Values

我正在使用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

你是...

  1. 談論顯示某種哈希鍵和值的排序顯示 ,或者
  2. 居然以某種方式重新排列了哈希的內部結構? 這樣,例如,對myhash.keys的調用總是按特定順序返回事物?

如果2,為什么? 您正在吠錯樹。 哈希只是與值的鍵的協會,如果你正在做什么 ,它的鍵事項的順序,(比試圖讓一個漂亮的/可讀的顯示等),你要的東西走錯了路。

查看這篇文章,獲得比我的文章更清晰的解釋: http : //www.rubyinside.com/how-to/ruby-sort-hash

暫無
暫無

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

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