{"work"=>"Carpenter", "age"=-6ren">
gpt4 book ai didi

Ruby 遍历哈希的哈希

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:19 25 4
gpt4 key购买 nike

我有以下数组,正在努力根据我的需要对其进行格式化。

consolidated = [
{:name=>"Bob", :details=>{"work"=>"Carpenter", "age"=>"26", "Experience"=>"6"} },
{:name=>"Colin", :details=>{"work"=>"painting", "age"=>"20", "Experience"=>"4"} }
]

我正在尝试将其格式化如下:

Bob    work         Carpenter
age 26
Experience 6

Colin work painting
age 20
Experience 4

我尝试了以下方法:

require 'csv'
CSV.open("output.csv", "wb") do |csv|
csv << ["name", "nature", "details"]
consolidated.each do |val|
csv << [val[:name], val[:details]]
end
end
#=> [{:name=>"Bob", :details=>{"work"=>"Carpenter", "age"=>"26", "Experience"=>"6"}},
# {:name=>"Colin", :details=>{"work"=>"painting", "age"=>"20", "Experience"=>"4"}}]

但它会打印以下内容

name      nature                                                  details

Bob "work"=>"Carpenter", "age"=>"26", "Experience"=>"6"

Colin "work"=>"painting", "age"=>"20", "Experience"=>"4"

我不确定如何从第一个循环迭代散列的散列以获得预期的格式。

谢谢。

最佳答案

这里有一些可以帮助您入门的内容:

require 'csv'
data = [
{:name => "Bob", :details=>{"work"=>"Carpenter", "age"=>"26", "Experience"=>"6"}},
{:name => "Colin", :details=>{"work"=>"painting", "age"=>"20", "Experience"=>"4"}}
]

str = CSV.generate do |csv|
data.each do |datum|
datum[:details].each do |detail_key, detail_value|
csv << [datum[:name], detail_key, detail_value]
end
end
end

puts str
# >> Bob,work,Carpenter
# >> Bob,age,26
# >> Bob,Experience,6
# >> Colin,work,painting
# >> Colin,age,20
# >> Colin,Experience,4

简单地迭代所有细节并为那里的每个键值对发出一个新行,添加一个人的名字。

这将使您几乎得到您所需要的。部分之间只缺少空白行,并且人名在每一行上都是重复的。了解如何添加这些改进将是您的功课。

关于Ruby 遍历哈希的哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51099655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com