While reading Programming Ruby, I ran across this code snippet:
while gets
num1, num2 = split /,/
end
While I intuitively understand what it does, I don’t understand the syntax. ‘split’ is a method on the String class – in Ruby parlance, which string is the receiver of the ‘split’ message in the scenario above?
I can see in the docs that ‘gets’ assigns its result to the variable $_, so my guess is that it is implicitly using $_ as the receiver – but a whole bunch of Google searching has failed to confirm that guess. If that is the case, I’d love to know what general rule for methods called without an explicit receiver.
I did try the code in irb, with some diagnostic puts calls added, and I verified that the actual behavior is what you would expect – num1 and num2 get assigned values that were input separated by a comma.
Ruby 1.8 has a method
Kernel#split([pattern [, limit]])which is identical to$_.split(pattern, limit), andgetssets the value of$_.