Created
October 21, 2009 21:50
-
-
Save briandoll/215495 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The interesting world of the asterisk in Ruby: | |
Of course we can multiply with it and it's quite handy in a regex, but there are two other interesting uses. | |
First, variable arguments in the method signature: | |
def hmm(*args) | |
first, *rest = *args | |
puts first.inspect | |
puts rest.inspect | |
end | |
So we can pass any number of things: | |
>> hmm(1,2,3,4,5,6) | |
1 | |
[2, 3, 4, 5, 6] | |
>> hmm([1,3,4],4,5,6) | |
[1, 3, 4] | |
[4, 5, 6] | |
We can see another use of the asterisk in this method here: | |
first, *rest = *args | |
The first argument is assigned to the variable "first" and everything else is globbed together into an array, assigned to "rest". | |
BUT.... | |
There is another awesome yet mysterious use of our beloved asterisk. It can be used to convert an array into the raw form of it's elements, essentially unwrapping its contents. | |
For example: | |
>> a, b, c = *[:a, :b, :c] | |
=> [:a, :b, :c] | |
>> puts a.inspect | |
:a | |
>> puts b.inspect | |
:b | |
>> puts c.inspect | |
:c | |
This is equivalent to: | |
>> a, b, c = :a, :b, :c | |
Now lets use that in a method call: | |
>> array = [:a, :b, :c] | |
=> [:a, :b, :c] | |
>> hmm(*array) | |
:a | |
[:b, :c] | |
We can even mix "regular" arguments with it: | |
>> hmm("awesome", *array) | |
"awesome" | |
[:a, :b, :c] | |
Sweet! Now let's add stuff to that array in the same expression: | |
>> hmm(*array + [:d, :e, :f]) | |
:a | |
[:b, :c, :d, :e, :f] | |
=> nil | |
Let's add an argument *after* that array expansion! | |
>> hmm(*array, "oh snap") | |
SyntaxError: compile error | |
(irb):22: syntax error, unexpected tSTRING_BEG, expecting tAMPER | |
hmm(*array, "oh snap") | |
^ | |
(irb):22: syntax error, unexpected ')', expecting $end | |
from (irb):22 | |
OH SNAP! | |
It would seem that this "convert an array to a raw list of its elements" usage of our beloved asterisk does something extra. | |
What is it doing? Where is this implemented in the interpreter? What is this usage of the asterisk actually called? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment