DEV Community 👩‍💻👨‍💻

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

Posted on • Originally published at

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

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]
# { foo: 1, bar: 2, baz: 3 }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.