简体   繁体   中英

Ruby: skips over a gets value

I have a file check and sort script. Now I wanted the user to be to choose how he/she wishes to have the final output sorted. Sadly Ruby seems to ignore the gets command. If I comment out the entire section the script finishes just fine. Please ignore the def readout. I never finished that one....

So my question is: Why does Ruby skip over the gets command.

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

The Kernel#gets method reads from ARGF not $stdin . This means that if command line arguments were given (or more accurately if ARGV is not empty) it reads from the files in ARGV. Only otherwise does it read from stdin.

To always read from stdin, use $stdin.gets instead of gets .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM