What Does the * (Star) Mean in Ruby

What does the * (star) mean in Ruby?

Variable Length Argument List, Asterisk Operator

The last parameter of a method may be preceded by an asterisk(*), which is sometimes called the 'splat' operator. This indicates that more parameters may be passed to the function. Those parameters are collected up and an array is created.

The asterisk operator may also precede an Array argument in a method call. In this case the Array will be expanded and the values passed in as if they were separated by commas.

What does the (unary) * operator do in this Ruby code?

The * is the splat operator.

It expands an Array into a list of arguments, in this case a list of arguments to the Hash.[] method. (To be more precise, it expands any object that responds to to_ary/to_a, or to_a in Ruby 1.9.)

To illustrate, the following two statements are equal:

method arg1, arg2, arg3
method *[arg1, arg2, arg3]

It can also be used in a different context, to catch all remaining method arguments in a method definition. In that case, it does not expand, but combine:

def method2(*args)  # args will hold Array of all arguments
end

Some more detailed information here.

What does the * mean in this recursive ruby function?

The star (in this case) stands for array unpacking. The idea behind it is that you want to get one array with the given elements, instead of array of array, element, array:

left  = [1, 2, 3]
pivot = 4
right = [5, 6, 7]

[left, pivot, right] # => [[1, 2, 3], 4, [5, 6, 7]]

[*left, pivot, *right] # => [1, 2, 3, 4, 5, 6, 7]

How you do specify multiple arguments or parameters in Thor?

Yes, there is another way of doing this.

require 'thor'
class TestApp < Thor
desc "hello NAMES", "long desc"
def hello(*names)
say "hello #{names.join('; ')}"
end
end

And it can be called like this:

$ thor test_app:hello first second third
hello first; second; third


Related Topics



Leave a reply



Submit