DEV Community

Cover image for Today I learned about the splat operator in Ruby.
Patrick Wendo
Patrick Wendo

Posted on • Edited on

4 2

Today I learned about the splat operator in Ruby.

Background

In my use case, I wanted to pass an array of fields into the .pluck operator for a query, but the pluck operator doesn't take in arrays. Obviously, the solution here is to destructure the array. Were it JS I probably would have just written .pluck(...pluck_fields) and moved on with my life. But funny enough, I have never had to destructure an array within function arguments. So I asked my supervisor and they told me to check the splat operator.

Splat Operator (* & **)

According to this article by Starr Horne, **They (splat operators) let you pass an array into a function expecting multiple arguments. The first item in the array becomes the first argument, the second item becomes the second argument and so on.*

Splat operator is more commonly used in function definition when the number of arguments is not known before hand, for instance:

def fun(*args)
    p args
end
Enter fullscreen mode Exit fullscreen mode

But in my use case, I want to focus on the first definition I mentioned, they can be used to pass an array into a function expecting multiple arguments. This directly solves my problem, where now i can pass an array of fields I want plucked to the pluck function,

.pluck(*pluck_fields)
Enter fullscreen mode Exit fullscreen mode

There is a lot more to explain about the splat operator and how it can also destructure Hashes as well, but that is beyond the scope of this post for now. ( This Post also explains it better )

SPLAT!!!!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (3)

Collapse
 
swiknaba profile image
Lud
a = { foo: "bar" }

b = {
  bar: "baz",
  **a
}

puts b
> {
  bar: "baz",
  foo: "bar",
}
Enter fullscreen mode Exit fullscreen mode

;)

Collapse
 
w3ndo profile image
Patrick Wendo

This is definitely one of those operators you learn about and then suddenly realise how much easier it makes life.

Collapse
 
michaeltharrington profile image
Michael Tharrington

Lol, love the cover image ya chose here!

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️