问题:
我有以下哈希值:
哈希= {1 => {:price =>“ 400”,:brand =>“ Primark”},2 => {:price =>“ 1000”, :brand =>“ pull&bear”},3 => {:price =>“ 1700”,:brand =>“”}, 4 => {:price =>“ 500”,:brand =>“ H&M”},5 => {:price =>“ 500”, :brand =>“ Mango”}}
,我想将其转换为csv文件。
目前为止的方法:
我最接近的解决方案(inspired by)似乎会不断覆盖自身:
require 'csv'
(1..5).each do |id|
column_names = hash[id].keys
column_values = hash[id].values
s=CSV.generate do |csv|
csv << column_names
csv << column_values
end
File.write('the_file.csv', s)
end
当前的csv文件:
+---+------------+-------------+
| | A | B |
+---+------------+-------------+
| 1 | price,brand| |
| 2 | 500, Mango | |
+---+------------+-------------+
所需的csv输出:
+---+------------+-------------+
| | A | B |
+---+------------+-------------+
| 1 | price | brand |
| 2 | 400 | Primark |
| 3 | 1000 | pull&bear |
| 4 | 1700 | |
| 5 | 500 | H&M |
| 6 | 500 | mango |
+---+------------+-------------+
这里有几个问题,这些问题要么处理反操作(将csv转换为嵌套的哈希),要么仅将简单的哈希转换为csv文件,但不使用嵌套的哈希。我是Ruby的新手,现在还无法联系。帮助将不胜感激!
答案 0 :(得分:4)
似乎您只对嵌套哈希的值感兴趣。在这种情况下,您只需完成
##test_views.py
def test_call_view_loads(self):
product = Product.objects.get(id=1)
response = self.client.get(f'/shop/{product.id}/{product.slug}/')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'shop/product/Product_detail.html')
(更新)
标题应展平为一个简单的数组。
答案 1 :(得分:4)
我会做这样的事情:
require 'csv'
CSV.open('the_file.csv', 'w') do |csv|
hash.each do |id, attributes|
csv << [id, *attributes.values_at(:price, :brand)]
end
end
答案 2 :(得分:1)
CSV格式本质上是一个数组数组。主数组的每个元素都是一行。单行是单元格的数组。所以您基本上想要的是这样的:
[
[:price, :brand],
["400", "Primark"],
["1000", "Pull&Bear"]
]
您可以通过以下方式实现它:
headers = hash.values[0].keys # this will return [:price, :brand] and we'll use it as a header
data = hash.values.map(&:values)
csv_output = CSV.generate do |csv|
csv << headers # we need headers only once, we don't need them in every row
data.each do |single_row| # iterate over each row
csv << single_row # add the row to csv file
end
end
File.write('the_file.csv', csv_output)
此代码假定每一行都有所有可用数据(即每一行都有价格和品牌)。上面由用户重写提供的代码更加灵活。