I'm going to assume the two pieces which are confusing are ||=
and *command
.
||=
is a conditional assignment operator which only performs an assignment when the variable on it's left side evaluates to false
, typically when it is nil
or false
. This is very commonly used with instance variables, or hash members, both of which evaluate to nil when unset.
*
is a splat operator and is used to convert an Array to a series of arguments passed into a method. The following examples are identical:
# Pass colors directly to use_colors.
use_colors('red', 'green', 'blue')
# Unpack an Array into an argument list for use_colors.
colors = ['red', 'green', 'blue']
use_colors(*colors)
Likewise, you can use the splat operator in a method declaration to receive the remaining passed arguments as an Array:
# This method can accept any number of colors, including zero.
def use_colors(*colors)
colors.each do |color|
puts "Using color: #{color}!"
end
end