NOTE. mischa splat on GitHub contains many interesting interactive examples * in action.
By googling, I found that one way to iterate over a range of numbers in Ruby (your classic C-style loop for a loop)
for (i = first; i <= last; i++) { whatever(i); }
should do something like this
[*first..last].each do |i| whatever i end
But what exactly happens with this syntax [*first..last] ? I played with irb and I see this:
ruby-1.9.2-p180 :001 > 0..5 => 0..5 ruby-1.9.2-p180 :002 > [0..5] => [0..5] ruby-1.9.2-p180 :003 > [*0..5] => [0, 1, 2, 3, 4, 5] ruby-1.9.2-p180 :004 > *0..5 SyntaxError: (irb):4: syntax error, unexpected tDOT2, expecting tCOLON2 or '[' or '.' *0..5 ^
Everything I've read on the Internet discusses a unary asterisk as useful for expanding and collapsing arguments passed to a method, useful for variable-length argument lists
def foo(*bar) bar end foo 'tater' # => ["tater"] foo 'tater', 'tot' # => ["tater", "tot"]
and I get this, but I donโt see how this relates to the extension running in my example block above.
To be clear, I know that The Ruby Way is intended to iterate over an array or collection, and not to use the length of the array and iterate through an integer index. However, in this example, I am really dealing with a list of integers. :)
operators syntax ruby splat
Justin force
source share