Reputation: 853
In the following script:
first, second, third = ARGV
puts "The oldest brothers name is #{first}"
puts "The middle brothers name is #{second}"
puts "The youngest brothers name is #{third}"
puts "What is your moms name?"
mom = $stdin.gets.chomp
puts "What is your dads name?"
dad = $stdin.gets.chomp
puts "In the my family there are three sons #{first}, #{second}, #{third}, and a mom named #{mom}, and a father named #{dad}"
I cannot accept user input using the gets
command without the $stdin
. I have to use $stdin.gets
in order for this to work.
Why is that? What does the ARGV
do that disables this? Is $stdin
not included by default with the gets
command?
Upvotes: 1
Views: 211
Reputation: 7223
From the gets function documentation:
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.
So, if you pass command line arguments to your ruby program, gets
will no longer read from $stdin
but instead from those files you passed.
Imagine we had a shorter example of your code in a file called argv.rb
:
first, second = ARGV
input = gets.chomp
puts "First: #{first}, Second: #{second}, Input #{input}"
And we created the following files:
$ echo "Alex" > alex
$ echo "Bob" > bob
And we run our program like ruby argv.rb alex bob
, the output would be:
First: alex, Second: bob, Input Alex
Note that the value of input
is "Alex", because that was the contents of the first file 'alex'. If we were to call gets
a second time, the value returned would be "Bob" because that's what's inside the next file, "bob".
Upvotes: 2