简体   繁体   English

如何构造嵌套在红宝石中的倍数的哈希

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

I want to construct a hash, the problem is that I have some customers that are buyers and others that are sellers that can have the same name and I need to group them in a hash by name. 我想构造一个哈希,问题是我有一些客户是买方,而有些是卖方,它们可以具有相同的名称,因此我需要按名称将它们分组在哈希中。 Something like this: 像这样:

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

The name is the key and the value is the hash with buyers and sellers, but I don't know how to initialize the hash and how to add a new key, value. 名称是键,值是买卖双方的哈希值,但是我不知道如何初始化哈希值以及如何添加新的键值。 Suppose that I have the Customer.all and I can for example ask: 假设我有Customer.all ,例如,我可以问:

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

You can use the block form of Hash.new to set up each hash key that does not have a corresponding entry, yet, to have a hash as its value with the 2 keys you need: 您可以使用Hash.new的块形式来设置每个没有相应条目的哈希键,但要使用所需的2个键将哈希值作为其值:

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

and then you can loop through and assign to either the :buyers or :sellers subarray as needed: 然后可以遍历并根据需要分配给: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]}}

For those following along at home, this is the Customer class I used for testing: 对于那些在家中跟随的人,这是我用于测试的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

Solution: 解:

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

Pls, refer the following link to know more about Hash and nested Hash 请通过以下链接了解有关哈希嵌套哈希的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM