DEV Community

Cover image for 5 Ways to Splat in Ruby
Jason Dinsmore for Hint

Posted on • Originally published at hint.io

5 Ways to Splat in Ruby

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!

hopping rabbit

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)