Forum: Ruby gets bug?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F330a44fdf083a7a30488efc47759f3f?d=identicon&s=25 Shea Martin (Guest)
on 2006-01-04 18:12
(Received via mailing list)
<snip>
if ARGV.size > 0
    puts "first arg is #{ARGV[0]}"
end
puts "enter text"
ans = gets
puts "you said #{ans}"
</snip>

Run this code, as ./test.rb.  Then run it with an command line arg, like
"./test.rb -x".  And you will get an error like this:

   "test.rb:3:in `gets': No such file or directory - -x (Errno::ENOENT)"

The fix I have found, is to change gets to $stdin.gets.  I saw some
traffic on the mailing list archives regarding this, but no resolution.

Is this expected behaviour?
ruby -v is: ruby 1.8.3 (2005-09-21) [sparc-solaris2.10]

Thanks,

~S
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-01-04 18:14
(Received via mailing list)
On Jan 4, 2006, at 9:17 AM, Shea Martin wrote:

> Run this code, as ./test.rb.  Then run it with an command line arg,
> like "./test.rb -x".  And you will get an error like this:
>
>   "test.rb:3:in `gets': No such file or directory - -x
> (Errno::ENOENT)"
>
> The fix I have found, is to change gets to $stdin.gets.  I saw some
> traffic on the mailing list archives regarding this, but no
> resolution.
>
> Is this expected behaviour?

Yes it is.  Kernel.gets() reads from files specified as command-line
options or STDIN, if none were given.  This makes it easy to write
Unix-style filters.

You can always shift the option out of ARGV before calling gets()
with something like:

if ARGV.first == "-x"
   ARGV.shift
   # ...
end

Hope that helps.

James Edward Gray II
F0b26d242cc8af969cb83b045d679348?d=identicon&s=25 Gary Watson (Guest)
on 2006-01-04 18:14
(Received via mailing list)
Shea Martin wrote:
> Run this code, as ./test.rb.  Then run it with an command line arg, like
> Thanks,
>
> ~S

I've run into this problem before as well, somebody pointed me to the ri
documentation on Kernel#gets, it says the following.

Returns the next line from the list of files in +ARGV+, or from standard
input if no files are present on the command line. Returns +nil+ at end
of file.

Hope this helps.
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 Robert Klemme (Guest)
on 2006-01-04 18:17
(Received via mailing list)
James Edward Gray II wrote:
>> </snip>
>>
>    ARGV.shift
>    # ...
> end

I'd prefer to use OptionParser.parse! for this - but otherwise totally
agree.

    robert
This topic is locked and can not be replied to.