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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With