Maximum flexibility in Ruby method arguments with the splat operators

posted by Ayush Newatia
18 June, 2021



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

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

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

  ...
end

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!