Arrays and the splat operator

suggest change

The \* operator can be used to unpack variables and arrays so that they can be passed as individual arguments to a method.

This can be used to wrap a single object in an Array if it is not already:

def wrap_in_array(value)
  [*value]
end

wrap_in_array(1)
#> [1]

wrap_in_array([1, 2, 3])
#> [1, 2, 3]

wrap_in_array(nil)
#> []

In the above example, the wrap_in_array method accepts one argument, value.

If value is an Array, its elements are unpacked and a new array is created containing those elements.

If value is a single object, a new array is created containing that single object.

If value is nil, an empty array is returned.

The splat operator is particularly handy as a parameter. It gathers every argument into one array, so the method can take a single value or several:

def list(*values)
  values.each do |value|
    # do something with value
    puts value
  end
end

list(100)
#> 100

list(100, 200)
#> 100
#> 200

list(nil)
#>
# puts nil writes a blank line

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents