2

3行のテキストファイルを開きたい

722.49 のテレビ 3 台

14.99で卵1カートン

34.85で2足の靴

そしてそれをこれに変えます:

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
4

4 に答える 4

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
于 2013-02-02T01:37:11.200 に答える
1
File.open("order.txt", "r") do |f|
  n,h = 0,{}
  f.each_line do |line|
    n += 1
    line =~ /(\d) (.*) at (\d*\.\d*)/
    h[n.to_s] = { :quantity => $1.to_i, :item => $2, :price => $3 }
  end
end
于 2013-02-01T05:05:37.940 に答える
1
hash = File.readlines('/path/to/your/file.txt').each_with_index.with_object({}) do |(line, idx), h|
  /(?<quantity>\d+)\s(?<item>.*)\sat\s(?<price>\d+(:?\.\d+)$)/ =~ line
  h[(idx + 1).to_s] = {:item => item, :price => price.to_f, :quantity => quantity.to_i}
end
于 2013-02-01T05:04:45.063 に答える