1

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

It is more reliable to always use $stdin.gets instead of gets

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.