Ruby Splat operator

Topics: Ruby

The splat operator *<operand> in Ruby does two things. It either deconstructs an array into its separate elements, or it does the opposite.

Use case: class method call, instance method implementation

The mirrored effect of the splat operator lets us build a nice shorthand that allows us to call a class method but implement the business logic as instance methods, which prevents side effects due to the object’s limited lifetime.

With the splat trick, we can simply call Foo.perform(...) instead of Foo.new(...).perform.

def self.perform(*args)
  new(*args).perform 
end

Here, the perform class method collects all its arguments in a single variable, instantiates an object of itself, and finally calls the object’s perform method with the list of arguments, expanded from the variable again.