SittingBull SittingBull - 4 months ago 8
Ruby Question

Why my "gets" is not taking user input but rather printing the first line in the comment?

I started to learn ruby. I have the following code:

=begin file_new = File.new("temp.txt","w")

file_new.puts............................
.........................................

=end

puts "What is your name?"


name = gets

puts "Hello"+name+"! How are you?"


Without letting me entering my input, it's printing the following:

What is your name?
Hello=begin file_new = File.new("temp.txt","w")
! How are you?


Why it's reading my commented previous code segment instead of taking user input?

Edit

So I deleted the multi line comments and getting the following:

What is your name?
Helloputs "What is your name?"! How are you?


Edit2:
This is the output after putting
p ARGV
to the beginning of the script.

C:\RubyWorkSpace>ruby ruby.rb
["ruby.rb"]
What is your name?
Hellop ARGV! How are you?

Answer

When your script is invoked with command line arguments, gets will interpret them as a list of file and read from those files rather than from stdin. This is meant as a shortcut to create scripts acting like grep and similar command line tools, which will process the given files or stdin if no files were given (making it easy to pipe input to them in shell scripts). If you always want to read from stdin, you should use STDIN.gets.

In your case you don't seem to be invoking your script with any command line arguments, but you actually are: due to the way Windows handles file extensions in the command line, you can just type in foo to start a ruby script named foo.rb. Your script is named ruby.rb and when you type in ruby, Windows actually executes your script ruby.rb rather than ruby.exe, the Ruby interpreter. So ruby ruby.rb actually invokes your script ruby.rb with the argument ruby.rb. To invoke your script without arguments, just type ruby, ruby.rb or, if you want to invoke the interpreter explicitly ruby.exe ruby.rb. You can also rename your script to something other than ruby to avoid this problem.

Comments