I'm new to learning ruby and currently stuck on having ARGV and gets.chomp in the same script.
I want the script to unpack 3 arguments first then I'll ask a question (gets.chomp) and then print string which includes one of the ARGV and gets.chomp variables. In the terminal I'm setting the ARGV as one two three (example: ruby file1.rb one two three). Example below of code:
first, second, third = ARGV
puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"
This works exactly how I would expect. In the terminal, it gives me one, two and three as variables in first, second and third.
I've added in a puts "What is your favourite colour" and this prints out as expected but when I set a gets.chomp for the input, I get an error.
first, second, third = ARGV
puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"
puts "What is your favourite colour? "
colour = gets.chomp #this is where the error occurs
puts "So your favourite number is #{first} and you like the colour #{colour}."
^The bottom line is what I want to print but I get an error at gets.chomp
This is what the terminal prints:
$ ruby ex13.rb one two three
Your first variable is: one
Your second variable is: two
Your third variable is: three
What is your favourite colour?
ex13.rb:8:in `gets': No such file or directory - one (Errno::ENOENT)
from ex13.rb:8:in `gets'
from ex13.rb:8:in `<main>'
I hoped I've explained the above well enough and let me know if any more information is needed.
Any help will be greatly appreciated!
Thanks,
I answered a question about this yesterday, which you can read here, but to address your situation specifically:
After first, second, third = ARGV
, call ARGV.clear
to empty it out.
Alternatively you could do first, second, third = 3.times.map { ARGV.shift }
The reason is that gets
reads from ARGV if there's anything in it. You need to empty ARGV out before calling gets
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With