我想打开一个三行文本文件
722.49 的 3 台电视
1 箱鸡蛋 14.99
2 双鞋 34.85
然后把它变成这样:
hash = {
"1"=>{:item=>"televisions", :price=>722.49, :quantity=>3},
"2"=>{:item=>"carton of eggs", :price=>14.99, :quantity=>1},
"3"=>{:item=>"pair of shoes", :price=>34.85, :quantity=>2}
}
我很困惑,不知道该怎么做。这是我到目前为止所拥有的:
f = File.open("order.txt", "r")
lines = f.readlines
h = {}
n = 1
while n < lines.size
lines.each do |line|
h["#{n}"] = {:quantity => line[line =~ /^[0-9]/]}
n+=1
end
end
最佳答案
没有理由让这么简单的东西看起来很丑!
h = {}
lines.each_with_index do |line, i|
quantity, item, price = line.match(/^(\d+) (.*) at (\d+\.\d+)$/).captures
h[i+1] = {quantity: quantity.to_i, item: item, price: price.to_f}
end
关于ruby - 读取文本文件,解析它,并将其存储到哈希中。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14639805/