Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing splat on nil as argument

All values for b below let me call a method with the *args syntax.

def some_method(a)
   puts a
end

b = 1
some_method(*b) # => 1

b = false
some_method(*b) # => false

b = "whatever"
some_method(*b) # => "whatever"

With nil, I expected to get nil, not argument error:

b = nil
some_method(*b) # => ArgumentError: wrong number of arguments (0 for 1)

What is happening here?

like image 593
Automatico Avatar asked Jun 01 '14 23:06

Automatico


1 Answers

The splat operator * first applies to_a to the object if it is not an array and to_a is defined on it. For numerals, falseclass, and strings, to_a is not defined, and they remain themselves. For nilclass, to_a is defined and returns an empty array. When they are splatted, the numerals, falseclass, and strings remain themselves, but the empty array becomes absence of anything. Also see an answer to this question.

like image 63
sawa Avatar answered Oct 08 '22 03:10

sawa