我有一个产品文件,列出了商品#,产品和价格。我想阅读这个文件,并将其初始化为哈希,项目#是关键,产品和价格是价值。这是我的文件
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"]
答案 0 :(得分:11)
我将您的数据保存为名为products.csv
的CSV文件并执行了此操作:
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
可以更简洁的方式实现相同的结果,但它会立即将整个文件读入内存,如果文件很大,这可能不是一个好主意:
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最初建议的那样,还有一种更具功能性的方法:
require 'csv'
products = Hash[ CSV.read('products.csv').map do |row|
[ row[0].to_i, [row[1].strip,row[2].to_f] ]
end ]
答案 1 :(得分:1)
使用CSV转换器处理数据的变体:
require 'csv'
products = {}
CSV.foreach('products.csv', {col_sep: ', ', converters: :numeric}) do |row|
products[row.shift] = row
end
p products
#=> {199=>["Shoes", 59.99], 211=>["Shirts", 19.99], 245=>["Hats", 25.99], 689=>["Coats", 99.99], 712=>["Beanies", 6.99]}