ruby - 读取文本文件,解析它,并将其存储到哈希中。如何?

标签 ruby file

我想打开一个三行文本文件

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/

相关文章:

ruby - 使 Ruby block 返回一个数组?

ruby-on-rails - 未定义方法send_data

ruby - 根据字典匹配和替换 Ruby 数组

c - 为什么在这段代码中,fgets 不应该返回 null?

python - 去掉字符串中的\x## (Python)

c - 如何读取文件直到倒数第二行

包含所有文件信息的 C++ 文件列表

ruby-on-rails - Rails 教程第 1 章10 测试10.20失败

arrays - 从具有特定索引的数组的数组中选择项目

c - 在C中: File Not Found Error When using readInputFile function for a second time on fclose()