如何读取.txt文件并将其与用户输入进行比较,以查看它是否与Ruby匹配?

时间:2016-05-21 12:39:16

标签: ruby

我正在尝试读取.txt文件并查看是否在文件中找到了提供的用户输入(条形码),如果它不是我要告诉他们然后不将其包含在收据文件中(最后输出)。

(产品是数组[条形码(字符串),数量(字符串)]

  while line = file.gets
  line = line.split(",")
  products.each do |product|
  if line[0] != product[0]
    puts "Your item #{product[0]} could not be found in the stockfile. It will not be included in the receipt."
  end
  if line[0] == product[0] 
    receipt << [line[0],line[1],line[2]]
  end

Stockfile:

12636723,BenQ XL2411Z Monitor,29.99

12345670,Razer Deathadder Mouse,4.49

77766236,Lenovo Thinkpad X1 Carbon Laptop,65.00

现在意识到逻辑是有缺陷的,如果我要做上述事情,那么打印出来就不会发现很多次。我不知道我是否可以向逻辑寻求帮助。

1 个答案:

答案 0 :(得分:0)

不要反复使用滚轮,csv gem用于读取此类文件,我在此处从文件的DATA部分执行此操作,以便您可以运行此示例。 产品可以是结构或类,为了简洁我在这里使用哈希。

require "csv"

products = [{name: 'milk', barcode: 1},{name: 'butter',barcode: 2},{name: 'flour', barcode: 3}]
receipt  = []

stock = File.read('stock.csv', :col_sep => ",", :headers => true)
stock = CSV.parse(DATA, :col_sep => ",", :headers => true)
products.each do |product|
  if stock.find {|row| row['Name'] == product[:name]}
    receipt << product.to_a
  else
    puts "Your item #{product[:name]} could not be found in the stockfile. It will not be included in the receipt."
  end
end
__END__
   Name, Quantifier, Amount
milk, liter, 2
butter, gram, 250

哪个给出了

# Your item flour could not be found in the stockfile. It will not be included in the receipt.
# receipt: #[[[:name, "milk"], [:barcode, 1]], [[:name, "butter"], [:barcode, 2]]]