Ruby:跳过获取值

Ruby:跳过获取值,第1张

概述我有一个文件检查和排序脚本.现在我希望用户选择他/她希望如何排序最终输出.可悲的是 Ruby似乎忽略了gets命令.如果我注释掉整个部分,脚本就完成了.请忽略def读数.我从未完成那个…… 所以我的问题是:为什么Ruby会跳过gets命令. class Product attr_reader :id, :name, :price, :stock def initialize(id,name 我有一个文件检查和排序脚本.现在我希望用户选择他/她希望如何排序最终输出.可悲的是 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  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:跳过获取值所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1288612.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存