super
super lets a child class call the parent's version of the same method, like asking a parent how they did it first. You can then add your own part.
In this page:
Syntax
class ChildClass < ParentClass
def method_name(param)
super # or super(param)
# extra behavior
end
end
super
super calls the same-named method on the parent class from inside an overriding method, letting you extend rather than fully replace the parent's behavior.
Calling super with no parentheses automatically forwards all the current method's arguments; super() with empty parentheses calls the parent method with no arguments at all. This distinction is a common source of subtle bugs if you're not careful.
Warning:
super(no parens) forwards the current arguments automatically.super()(empty parens) calls the parent method with no arguments -- these are not the same.
Example: super
class Animal
def initialize(name)
@name = name
end
def describe
puts "I am #{@name}"
end
end
class Dog < Animal
def initialize(name)
super(name)
end
def describe
super
puts "...and I am a dog"
end
end
rex = Dog.new("Rex")
rex.describe
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Calling
superwith no parentheses and expecting no arguments, when it passes the current arguments automatically; usesuper()for none. - Forgetting
superininitialize, so parent's setup is skipped. - Using
superin a method that has no parent version, which raisesNoMethodError.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: