读取文本文件,解析它并将其存储到哈希中.怎么样?

Smo*_*oth 2 ruby file

我想打开一个包含三行的文本文件

3台电视722.49

1箱14.99的鸡蛋

两双鞋子在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}
       }
Run Code Online (Sandbox Code Playgroud)

我很不确定如何去做这件事.这是我到目前为止所拥有的:

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
Run Code Online (Sandbox Code Playgroud)

gle*_*ald 9

没有理由这么简单看起来很难看!

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
Run Code Online (Sandbox Code Playgroud)