簡體   English   中英

如何構造嵌套在紅寶石中的倍數的哈希

[英]how to construct a hash with multiples nested in ruby

我想構造一個哈希,問題是我有一些客戶是買方,而有些是賣方,它們可以具有相同的名稱,因此我需要按名稱將它們分組在哈希中。 像這樣:

customers = {"name1": {"buyers": [id11,..,id1n], "sellers": [ids1,..,ids1n]},
             "name2": {"buyers": [id2,..,id], "sellers": [id1,..,idn] }}

名稱是鍵,值是買賣雙方的哈希值,但是我不知道如何初始化哈希值以及如何添加新的鍵值。 假設我有Customer.all ,例如,我可以問:

Customer.all do |customer|
  if customer.buyer?
    puts customer.name, customer.id
  end
end

您可以使用Hash.new的塊形式來設置每個沒有相應條目的哈希鍵,但要使用所需的2個鍵將哈希值作為其值:

customers = Hash.new do |hash, key|
  hash[key] = { buyers: [], sellers: [] }
end

然后可以遍歷並根據需要分配給:buyers:sellers子數組:

Customer.all do |customer|
  group = customers[customer.name] # this creates a sub hash if this is the first
                                   # time the name is seen
  group = customer.buyer? ? group[:buyers] : group[:sellers]

  group << customer.id
end

p customers
# Sample Output (with newlines added for readability):
# {"Customer Group 1"=>{:buyers=>[5, 9, 17], :sellers=>[1, 13]},
#  "Customer Group 2"=>{:buyers=>[6, 10], :sellers=>[2, 14, 18]},
#  "Customer Group 3"=>{:buyers=>[7, 11, 15], :sellers=>[3, 19]},
#  "Customer Group 0"=>{:buyers=>[20], :sellers=>[4, 8, 12, 16]}}

對於那些在家中跟隨的人,這是我用於測試的Customer類:

class Customer
  def self.all(&block)
    1.upto(20).map do |id|
      Customer.new(id, "Customer Group #{id % 4}", rand < 0.5)
    end.each(&block)
  end

  attr_reader :id, :name
  def initialize(id, name, buyer)
    @id = id
    @name = name
    @buyer = buyer
  end

  def buyer?
    @buyer
  end
end

解:

hsh = {}
Customer.all do |customer|
 if customer.buyer?
    hsh[customer.id] = customer.name
end
puts hsh

請通過以下鏈接了解有關哈希嵌套哈希的更多信息

暫無
暫無

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

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