Ruby Language Arrays Arrays and the splat (*) operator

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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 element.

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 when used as an argument in methods in some cases. For example, it allows nil, single values and arrays to be handled in a consistent manner:

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)
# nothing is outputted


Got any Ruby Language Question?