从类似CSV的文件创建哈希 [英] Create a Hash from a CSV-like file
问题描述
我有一个产品文件列出项目#,产品和价格。我想读取这个文件,并将其初始化为一个哈希,项目#是关键,产品和价格是值。这是我的文件
I have a products file listing the item #, products, and price. I would like to read this file and initialize it as a hash with the item #'s being the key and the products and price being the value. Here is my file
199, Shoes, 59.99
211, Shirts, 19.99
245, Hats, 25.99
689, Coats, 99.99
712, Beanies, 6.99
我想它看起来像这样。
products = {
199 =>['Shoes', 59.99],
211 =>['Shirts', 19.99],
245 =>['Hats', 25.99],
689 => ['Coats', 99.99],
712 => ['Beanies', 6.99]
}
这是我可以想出的
products_file = File.open("files.txt")
products_hash = []
while ! products_file.eof?
product_hash = products_file.gets.chomp
print product_hash.split(', ')
end
这里是我想出的输出:
["199", "Shoes", "59.99"]
["211", "Shirts", "19.99"]
["245", "Hats", "25.99"]
["689", "Coats", "99.99"]
["712", "Beanies", "6.99"]
推荐答案
我将您的数据保存为名为 products.csv
的CSV文件,并执行此操作:
I saved your data as a CSV file called products.csv
and did this:
require 'csv'
products = {}
CSV.foreach("products.csv") do |line|
products[line[0].to_i] = [line[1].strip, line[2].to_f]
end
products
#=> {199=>["Shoes", 59.99], 211=>["Shirts", 19.99], 245=>["Hats", 25.99], 689=>["Coats", 99.99], 712=>["Beanies", 6.99]}
同样的结果可以在更简洁方式使用 each_with_object
,但它会立即将整个文件读入内存,如果文件很大,这可能不是一个好主意:
The same result can be achieved in a more concise way using each_with_object
, but it reads the whole file into memory at once, which may not be a good idea if the file is large:
require 'csv'
products = CSV.read("products.csv").each_with_object({}) do |line, h|
h[line[0].to_i] = [line[1].strip, line[2].to_f]
end
还有一个更实用的方法,如Phrogz最初建议的:
There's also a more functional approach, as originally suggested by Phrogz:
require 'csv'
products = Hash[ CSV.read('products.csv').map do |row|
[ row[0].to_i, [row[1].strip,row[2].to_f] ]
end ]
这篇关于从类似CSV的文件创建哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!