Reputation: 657
Hi I am making a simple ruby script practiced where I make a form using gets.chomp
and arguments, the problem is that when gets.chomp
use the script returns me an error when I apply the argument test
.
The code:
#!usr/bin/ruby
def formulario(quien)
while (1)
print "[+] Word : "
word = gets.chomp
print quien + " -> " + word
end
end
quien = ARGV[0]
formulario(quien)
The error:
[+] Word : C:/Users/test/test.rb:8:in `gets': No such file or directory @ rb_sysopen - test (Errno::E
NOENT)
from C:/Users/test/test.rb:8:in `gets'
from C:/Users/test/test.rb:8:in `formulario'
from C:/Users/test/test.rb:17:in `<main>'
Can anyone help?
Upvotes: 62
Views: 16352
Reputation: 694
I ran into this issue today in Ruby 3.1.2. I can also confirm that STDIN.gets avoids this problem. An alternative workaround is to set ARGV to an empty array prior to capturing input via gets. You can simply set
ARGV = []
gets.chomp # works fine here
or store them elsewhere if you must get input before you've dealt with them all
cli_args = ARGV.dup
ARGV.clear
gets.chomp # works fine here
Upvotes: 0
Reputation: 13
If your program handle empty argument nor non-empty argument. You can use this module (especially if you already use default gets
everywhere)
# A module that help to use method gets no matter what the file argument is
module InputHelper
# Handle input method based on its file argument
def gets
if ARGV.nil?
Kernel.gets
else
STDIN.gets
end
end
end
and then you could include it on your class
require 'input_helper'
class YourClass
...
include InputHelper
...
end
Upvotes: 0
Reputation: 27822
It looks like you want to the user to type some input by reading a line from STDIN
, the best way to do this is by calling STDIN.gets
and not gets
. So your line becomes:
word = STDIN.gets.chomp
This is documented as IO.gets
. STDIN
is an instance of IO
.
Right now, you're executing Kernel.gets
, which does something different (emphasis mine):
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.
This appears to behave like STDIN.gets
if ARGV
is empty, but is not the same thing, hence the confusion.
Upvotes: 116