A splat on a hash converts it into an array.
[*{foo: :bar}] # => [[:foo, :bar]]
Is there some hidden mechanism (such as implicit class cast) going on here, or is it a built-in primitive feature?
Besides an array, are nil
and hash the only things that disappear/change with the splat operator under Ruby 1.9?
Splat operator or start (*) arguments in Ruby define they way they are received to a variable. Single splat operator can be used to receive arguments as an array to a variable or destructure an array into arguments. Double splat operator can be used to destructure a hash.
The * (or splat) operator allows a method to take an arbitrary number of arguments and is perfect for situations when you would not know in advance how many arguments will be passed in to a method.
When you multiply two numbers in Python you use the multiplication operator “*”. print (2 * 2) Gives you 4. “*” can also be used for unpacking, in Ruby and other computer languages it is called the splat operator.
In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).
A splat will attempt an explicit conversion of an object to an Array.
To do this, it will send to_a
and expect an Array
as a result.
class Foo
def to_a
[1,2,3]
end
end
a, b, c = *Foo.new
a # => 1
If the object does not respond to to_a
, then there is no effect, e.g. [*42] == [42]
Many builtin classes implement to_a
. In particular:
Enumerable
)
Array
Hash
Range
IO
and File
Enumerator
Enumerator::Lazy
(Ruby 2.0)Set
and SortedSet
NilClass
MatchData
OpenStruct
Struct
Time
Matrix
and Vector
All these can thus be splatted:
match, group, next_group = *"Hello, world".match(/(.*), (.*)/)
group # => "Hello"
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