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
Problems with the Rails Console, Rvm and Readline
Using Instance Variables in Class Methods - Ruby
Installing Ruby on MAC Os X 10.8.2
Sum the Value of Array in Hash
Change the Binding of a Proc in Ruby
Why Does Code Need to Be Reloaded in Rails 3
Weird Imoperfection in Ruby Blocks
Ruby/Rails: Converting a Date to a Unix Timestamp
Rails: Should Partials Be Aware of Instance Variables
How to Pass Multiple Arguments to a Ruby Method as an Array
How Does Shovel (<<) Operator Work in Ruby Hashes
Database Configuration Does Not Specify Adapter
How to Reference a Function in Ruby
How to Enable C Extension Support in Jruby
How to Capture Values in Command Line and Add to Recipe
Role Does Not Exist and Unable to Create Database When Using Postgresql