5 Ways to Splat in Ruby

Jason Dinsmore - May 05, 2020

In honor of it being 5/5 today (aka Cinco de Mayo), I thought we'd continue the pattern and take a quick look at 5 different ways to use Ruby's infamous splat (*) operator.

Let's hop right into it!

hoppity hop

1. Interpolate Into an Array

Splat can be used to expand the contents of one array into another:

middle = %i(bar baz)
[:foo, *middle, :qux]

# [:foo, :bar, :baz, :qux]

2. Capture an Argument List

You can use splat to capture a list of arguments into an Array. Below, we're capturing the entire list of arguments being passed to foo into an Array named bar:

def foo(*bar)
  "#{bar.class.name}: #{bar}"

foo(:a, :b, :c)

# Array: [:a, :b, :c]

3. Capture First/Last or First/Rest Values

Splat can also be leveraged to split up an array into parts. Kinda like pattern matching:

arr = [1, 2, 3, 4, 5]
first, *, last = arr
puts first # 1
puts last # 5

first, *rest = arr
puts first # 1
puts rest # [2, 3, 4, 5]

4. Coerce a Value Into an Array

If you want to ensure the thing you are dealing with is an Array, you can splat it.

foo = 1
bar = *foo
puts bar # [1]

foo = [1, 2, 3]
bar = *foo
puts bar # [1, 2, 3]

5. Convert an Array Into a Hash

Lastly, splat can convert an Array into a Hash. Your Array needs to contain an even number of elements for this to work. If the Array were grouped into pairs, the first element in each pair will become a key in your Hash, and the second element of the pair will be the corresponding value.

arr = [:foo, 1, :bar, 2, :baz, 3]
# { foo: 1, bar: 2, baz: 3 }

Jason Dinsmore

Jason is a software engineer at Hint. He loves crafting great software, improving his fitness, and chillin' with any of his 5 dogs.


Ready to Get Started?