rubygets

Ruby gets reading from file given as argument


I have a ruby script that is run with ruby myscr.rb ./text_file.txt that reads input with gets and writes it to the file, but gets seems to be reading from the file and not terminal input. How do I force it to get input from the terminal in the same way as gets?


Solution

  • Kernel#gets is implemented that way on purpose (although it still surprised me, despite having worked in Ruby for many years):

    Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line.

    To read input only from the terminal, which comes into your script through the standard input stream, you can use the gets method directly on $stdin:

    File.open(ARGV.first, "w") do |f|
      f.puts($stdin.gets)
    end