'gets' has been hijacked

P

Pete Elmore

I was working with a simple script, that unexpectedly broke. The
problem can be reduced to this:

pete@robots:~$ cat t.rb
#!/usr/bin/env ruby
p gets
pete@robots:~$ ./t.rb
asdf
"asdf\n"
pete@robots:~$ ./t.rb nonexistent-file
/t.rb:2:in `gets': No such file or directory - nonexistent-file
(Errno::ENOENT)
from ./t.rb:2

Ah, right, I remember this from the Bad Old Days of Perl: stdin has been
stolen. Is there any way to stop this behavior, like a global I could
set or a flag I could pass to ruby? Couldn't find anything on the man
page or in Pickaxe.
 
J

James Edward Gray II

Yeah, that's what I'm doing. What I was wondering was if there was
something I could do to point Kernel#gets back at stdin.

I'm sure there is. Off the top of my head (untested!):

module Kernel
def gets() $stdin.gets end
end

But why not just ask Ruby for what you really meant in the first
place? ;)

James Edward Gray II
 
M

Mark Hubbart

On Jun 6, 2005, at 2:31 PM, Pete Elmore wrote:
=20
=20
gets() as you're using it calls Kernel.gets(), which basically
amounts to ARGF.gets(). That's very handy for building Unix filters.

expanding on that: ARGF *is* STDIN when there are no files specified:

mark@eMac% ruby -e'p ARGF.fileno =3D=3D STDIN.fileno'
true
mark@eMac% ruby -e'p ARGF.fileno =3D=3D STDIN.fileno' /etc/hosts
false
 
P

Pete Elmore

James said:
I'm sure there is. Off the top of my head (untested!):

module Kernel
def gets() $stdin.gets end
end
Ah, thanks. I'll probably just keep using $stdin.gets if there's not a
really clean way.
But why not just ask Ruby for what you really meant in the first
place? ;)
puts always goes to $stdout (well, $defout), so I thought that gets
would read $stdin, or it would be possible to nicely ask it to do so. I
don't mind $stdin.gets, but it seems a little odd. (I realize that I'm
treading dangerously close to POLSland, so I'll stop. :)
Hope that helps.
I'm always thankful to the community for tolerating my endless stream of
n00b questions. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top