我想构造一个哈希,问题是我有一些客户是买方,而有些是卖方,它们可以具有相同的名称,因此我需要按名称将它们分组在哈希中。像这样:
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
答案 0 :(得分:2)
您可以使用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
答案 1 :(得分:0)
解决方案:
hsh = {}
Customer.all do |customer|
if customer.buyer?
hsh[customer.id] = customer.name
end
puts hsh
请,请参考以下链接以进一步了解Hash和nested Hash