所以我的问题是:为什么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 endendproducts = []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解决方法 内核#从ARGF获取方法读取而不是$stdin.这意味着如果给出命令行参数(或者如果ARGV不为空则更准确),它将从ARGV中的文件中读取.只有这样才能从stdin中读取.
要始终从stdin读取,请使用$stdin.gets而不是gets.
总结以上是内存溢出为你收集整理的Ruby:跳过获取值全部内容,希望文章能够帮你解决Ruby:跳过获取值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)