On Dec 12, 2005, at 2:56 PM, Chad Perrin wrote:

> On Tue, Dec 13, 2005 at 03:46:09AM +0900, James Edward Gray II wrote:
>> On Dec 12, 2005, at 12:32 PM, William James wrote:
>>
>>> Also, as in Awk, "print" with no argument prints the line just read.
>>> Very simple.  If one needs to explicitly refer to the line just  
>>> read,
>>> one uses "$_".
>>>
>>> And "while gets" is simpler and clearer than "ARGF.each do |elem|".
>>
>> You would get a lot of support in Perland, but this kind of code is
>> very out of fashion in the Ruby community.
>
> I can see, for readability's sake, wanting to avoid non-explicit data
> handling like using "print" with no argument.

`while gets` is also "non-explicit".  It makes an assignment you do  
not see.  Compare with:

   ARGF ... each ... |line|

That shows the whole process:

   take the input files ... one line at a time ... and slot them  
right here

You would be surprised how hard the gets() version can make it to see  
errors.  Here's actual code from a Ruby Quiz submission, that  
certainly does not work as the author intended (though it may work  
fine in many cases):

   # ...

   if $0 == __FILE__
     cwstr = nil
     if FileTest.file?( ARGV[0] )
       File.open( ARGV[0] ) { cwstr = gets(nil) }
     end
     $stdout << CrossWord.build( cwstr )
   end

It took me a while to spot the issue.  How about you?

Many Rubyists also think something like `line` is prettier than $_.

I hear you though.  I came to Ruby through Perl and in the beginning,  
I used the default variable plenty.  I won't be surprised if you  
search the archives and find me on the other side of this  
discussion.  Now though, I've come to value Ruby's elegance and $_  
just looks wrong to me.  I guess you can say I'm assimilated.

The moral:  $_ works fine (for now!).  Use it if you like.  Ignore  
our sneers.  ;)

James Edward Gray II