Wednesday, January 10, 2007

Kernel#gets vs. IO#gets

I made an interesting discovery tonight while hacking on widi (it's actually quite embarrassing that I never came across this before). Whenever you are trying to read from stdin in ruby you typically just type 'gets' and don't think twice. I found out there are actually two different 'gets' methods, Kernel#gets and IO#gets.

Usually you don't notice the difference simply because if ARGV doesn't exist Kernel#gets simply reads from stdin. However, tonight I started building out some of the scm wrapper functionality of widi and naturally I was adding command line arguments. This caused widi to die a painful death. It's last words were:
kill #: widi.rb:27:in `gets': No such file or directory - kill (Errno::ENOENT)
from widi.rb:27

To fix the problem I googled a bit and realized I needed to explicitly tell ruby to check stdin using the global variable $stdin (IO#gets is private so don't even bother trying to call it!). Not exactly intuitive but I guess I can't complain too much.

No comments:

Tags

my google reader feed