我有一个文件检查和排序脚本。现在我希望用户选择他/她希望如何排序最终输出。可悲的是Ruby似乎忽略了gets命令。如果我注释掉整个部分,脚本就完成了。请忽略def读数。我从未完成那个......
所以我的问题是:为什么Ruby会跳过gets命令。
class Product
attr_reader :id, :name, :price, :stock
def initialize(id,name,price,stock)
@id = id
@name=name
@price=price
@stock=stock
end
def readout
self.each do |product|
print product.id
print "|"
print product.name
print "|"
print product.price
print "|"
print product.stock
puts ""
end
end
end
products = []
newproducts= []
if ARGV[0] != nil
if File.exist?(ARGV[0])
File.open(ARGV[0] , "r") do |f|
f.each_line do |line|
products << line
end
end
products.each do |product|
data = product.split(",")
newproducts.push(Product.new(data[0].strip, data[1].strip, data[2].strip.to_i, data[3].strip.to_i))
end
puts "What to sort by?"
question = gets.strip
if question == "name"
newproducts.sort! {|a,b| b.name <=> a.name}
elsif question == "price"
newproducts.sort! {|a,b| b.price <=> a.price}
elsif question =="id"
newproducts.sort! {|a,b| b.id <=> a.id}
elsif question == "stock"
newproducts.sort! {|a,b| b.stock <=> a.stock}
else
puts "Wrong Answer."
end
#End of File Check
else
puts "File #{ARGV[0]} does not exist."
end
if ARGV[1] != nil
File.open(ARGV[1], "w") do |f|
newproducts.each do |product|
puts "Added #{product.name} to the file."
data = {product.id, product.name, product.price, product.stock}
f.puts(data)
end
end
#End of ARGV check.
else
puts "No output file assigned."
end
#End of master ARGV check.
else
puts "No command given."
end
答案 0 :(得分:6)
Kernel#gets
方法从ARGF
而非$stdin
读取。这意味着如果给出了命令行参数(或者如果ARGV
不为空则更准确),它将从ARGV中的文件中读取。只有这样才能从标准输入读取。
要始终从标准输入读取,请使用$stdin.gets
代替gets
。