Hint

5 Ways to Splat in Ruby

Jason Dinsmore Originally published at hint.io ・2 min read

Originally posted on Hint's blog.

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!

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}"
end

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]
Hash[*arr]
# { foo: 1, bar: 2, baz: 3 }
``````

Posted on by:

Jason Dinsmore

I am a Rubist, doing what I love, in the state I was born in, with a great group of peeps @hint.

Hint

Hint is an agency with a passion for solving complex business problems and a knack for fixing broken software. How can we help you?