DEV Community

Discussion on: Today I learned about the splat operator in Ruby.

Collapse
 
jeremyf profile image
Jeremy Friesen

Welcome to the learning!

The * and ** are some of my favorite features; especially when you consider that if you have a hash with keys that are symbols you can prepend the ** and pass those as keyword args:

def my_method(hello:, gummy:)
  puts "Hello: #{hello}\nGummy: #{gummy}"
end

params = { hello: "world", gummy: "bears" }

my_method(**params)
Enter fullscreen mode Exit fullscreen mode

Which gets super cool when you have the case where params has more keys/values (e.g. params = { hello: "world", gummy: "bears", ninja: "turtle" })

You can then do the following:

more_params = { hello: "world", gummy: "bears", ninja: "turtle" }

my_method(**more_params.slice(:hello, :gummy))
Enter fullscreen mode Exit fullscreen mode

The above will only pass the :hello and :gummy values as named arguments.

The ** is a common pattern I use for dependency injection.

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
 
jeremyf profile image
Jeremy Friesen

Yes, and I'm excited to see where this learning takes you.