【问题标题】:how to construct a hash with multiples nested in ruby如何在ruby中构建具有多个嵌套的哈希
【发布时间】:2026-01-03 14:10:01
【问题描述】:

我想构造一个哈希,问题是我有一些客户是买家,而另一些客户是卖家,他们可以有相同的名称,我需要按名称将它们分组到一个哈希中。像这样的:

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

name是key,value是买家和卖家的hash,但是不知道hash怎么初始化,怎么添加新的key,value。 假设我有Customer.all,例如我可以问:

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

【问题讨论】:

  • 您能否编辑问题以在此处包含输入示例?
  • 您能否举例说明如何从数据库中获取名称以及如何知道谁是买家和卖家

标签: ruby-on-rails ruby


【解决方案1】:

您可以使用 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

【讨论】:

    【解决方案2】:

    解决方案:

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

    请参考以下链接了解更多关于Hashnested Hash的信息

    【讨论】: