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