Why does Ruby allow me to call the String method without specifying a string?

While reading Programming Ruby, I looked at this piece of code:

while gets num1, num2 = split /,/ end 

While I intuitively understand what he is doing, I do not understand the syntax. "split" is a method in the String class - in Ruby, which string is the recipient of the "split" message in the above script?

I can see in the documents that β€œgets” assigns its result to the variable $ _, so I assume that it implicitly uses $ _ as the recipient, but a whole bunch of Google searches did not confirm this hunch. If so, I would like to know which general rule for methods is invoked without an explicit recipient.

I tried the code in irb, with some diagnostic calls added, and I confirmed that the actual behavior is what you expect - num1 and num2 get the assigned values ​​that were entered separated by a comma.

+7
source share
2 answers

Ruby 1.8 has a Kernel#split([pattern [, limit]]) method that is identical to $_.split(pattern, limit) , and gets sets the value to $_ .

+6
source

You basically nailed it with your explanation (at least for 1.8.7, 1.9.3 they gave me NoMethodError for main ), but IMHO, what an awful Ruby (or maybe someone switched from Perl). If you rewrite it to something like this, it becomes much clearer:

 while input = gets.chomp num1, num2 = input.split(/,/) end 

A general rule for method calls without a receiver is that they are sent to self , regardless of what may be in the current context. At the top level, this is the main mentioned above, the crossover of $_ seems to have gone into 1.9.

+4
source

All Articles