Featured image

If you work with Ruby, you should know that arguments in methods can be set to a default value, for example:

def perform(arg: "default")
  # ...
end

But did you know that you can use instance variables as default values, like this:

class MyClass
  def initialize(arg)
    @arg = arg
  end
  def perform(arg = @arg)
    # ...
  end
end

Or (which is not at all obvious) other arguments of this method:

module MyModule
  def self.perform(a = nil, arg: a)
    # ...
  end
end

The latter case will help you gradually transition from positional arguments to keyword arguments. This is useful when you’re developing your own library and don’t want to drastically change its public interface.