On Thu, 25 Apr 2002, Kontra, Gergely wrote:

> Is it possible to use $_, if you don't specify variable for a block?
> So, if you happen to write
>
> a=array(1,4,1,5)
> a.each {
>   puts
> }
>
> It will prints 1
> 4
> 1
> 5
>
> Or this doecn't fits in ruby?
>
> (The idea came from perl)

I too miss this sometimes, especially when I chain methods, the |n|
donation sometimes take as many characters as the code itself. However, $_
doesn't make it particularly nice:

  [7,3,1,7,8,2,3,2].sort { |a,b| a <=> b }.map { |a| a**2 }

becomes

  [7,3,1,7,8,2,3,2].sort { $_[0] <=> $_[1] }.map { $_**2 }

This is more readable IMO:

  [7,3,1,7,8,2,3,2].sort { a <=> b }.map { a**2 }

I like this implicit stuff at work here, but I would perhaps create too
much conflict with other variables? How about allowing the |n| to be put
anywhere in the block?:

  [7,3,1,7,8,2,3,2].sort { |a| <=> |b| }.map { |a|**2 }

-- 
Lars Christensen, larsch / cs.auc.dk