加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby:跳过获取值

发布时间:2020-12-17 02:59:20 所属栏目:百科 来源:网络整理
导读:我有一个文件检查和排序脚本.现在我希望用户选择他/她希望如何排序最终输出.可悲的是 Ruby似乎忽略了gets命令.如果我注释掉整个部分,脚本就完成了.请忽略def读数.我从未完成那个…… 所以我的问题是:为什么Ruby会跳过gets命令. class Product attr_reader :
我有一个文件检查和排序脚本.现在我希望用户选择他/她希望如何排序最终输出.可悲的是 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

解决方法

内核#从ARGF获取方法读取而不是$stdin.这意味着如果给出命令行参数(或者如果ARGV不为空则更准确),它将从ARGV中的文件中读取.只有这样才能从stdin中读取.

要始终从stdin读取,请使用$stdin.gets而不是gets.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读