我有一个产品文件,列出了商品编号、产品和价格。我想要读取这个文件,并将其初始化为哈希表,其中商品编号是键,产品和价格是值。以下是我的文件:
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"]
tap
而不是each_with_object
。此連結提供了詳細的解釋。 - Phrogz