DEV Community

Ayush Newatia
Ayush Newatia

Posted on

Maximum flexibility in Ruby method arguments with the splat operators

Ruby has got to be one of the most malleable programming languages out there, which is why I like it so much.

Recently I was adding breadcrumbs to a Rails app and wrote a drop_breadcrumb method that could be called in a controller or controller action.

I wanted the call site to look like:

class MyController < ApplicationController
  drop_breadcrumb "Home", :home_path, except: :index

  def show
    drop_breadcrumb "Profile"
Enter fullscreen mode Exit fullscreen mode

As demonstrated above, only the first argument is compulsory. So I need a method signature that accepts:

  • A single argument for the label
  • Two arguments for the label and path
  • Two arguments for the label and an options hash
  • Three arguments for the label, path and an options hash

Ruby has the * (splat) and ** (double splat) operators for just that kind of flexibility! The splat operator allows a method to take a undefined number of arguments and the double splat operators allows an undefined number of keyword arguments.

Combining the two in the method definition will let us pass in any number of arguments with an optional options hash at the end! args can be then deconstructed into the individual values we need and we can use options like a regular Ruby hash:

def drop_breadcrumb(*args, **options)
  label, path = args

Enter fullscreen mode Exit fullscreen mode

It's always good to bear in mind to only use this level of flexibility when absolutely required as it's not very expressive for a reader. With the right use case though, as demonstrated above, it's a great tool to have in your toolbox!

Top comments (0)