“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey (contact@robl.me)
Senior Software Engineer, Brighton, UK

Calling super with no arguments

Suppose I want to overwrite a method an apply a optional argument that the original method didn’t accept.

class Something < ActiveRecord::Base

  def to_s(or_other = nil)
      if or_other
        Other.new.to_s
      else
        super
      end
  end

end

Seems fine. However, when you call to_s you’d get an error like wrong number of arguments (1 for 0). The reason is because without supply arguments to super they, by default, use the arguments passed to the overridden method. Since the original method didn’t accept any arguments previously then this fails. In order to avoid this you must call super() to deliberatly call it without arguments.

class Something < ActiveRecord::Base

  def to_s(or_other = nil)
      if or_other
        Other.new.to_s
      else
        super()
      end
  end

end