0
0
Rubyprogramming~5 mins

Method overriding in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is method overriding in Ruby?
Method overriding in Ruby is when a subclass provides its own version of a method that is already defined in its superclass. This allows the subclass to change or extend the behavior of that method.
Click to reveal answer
beginner
How does Ruby decide which method to call when a method is overridden?
Ruby calls the method defined in the subclass if it exists. If not, it looks up the inheritance chain to find the method in the superclass.
Click to reveal answer
intermediate
Can you override a method and still call the original method from the superclass in Ruby? How?
Yes, you can use the keyword super inside the overriding method to call the original method from the superclass.
Click to reveal answer
intermediate
What happens if you call super without parentheses and arguments in an overriding method?
Ruby automatically passes all the arguments received by the overriding method to the superclass method when you call <code>super</code> without parentheses.
Click to reveal answer
beginner
Show a simple example of method overriding in Ruby.
class Animal
  def speak
    "Hello"
  end
end

class Dog < Animal
  def speak
    "Woof!"
  end
end

puts Dog.new.speak  # Output: Woof!
Click to reveal answer
What keyword is used in Ruby to call the superclass method from an overriding method?
Abase
Bparent
Csuper
Doverride
If a subclass overrides a method but does not call super, what happens?
AThe superclass method is called automatically.
BThe superclass method is ignored.
CAn error occurs.
DBoth methods run in sequence.
What will this code output? class A def greet "Hi" end end class B < A def greet super + ", there!" end end puts B.new.greet
AError
B"Hi"
C", there!"
D"Hi, there!"
Which of these is true about method overriding?
AIt allows a subclass to change the behavior of a method from its superclass.
BIt creates a new method unrelated to the superclass.
CIt deletes the superclass method.
DIt only works with private methods.
In Ruby, if you want to pass different arguments to the superclass method when overriding, what should you do?
ACall <code>super</code> with the new arguments explicitly.
BCall <code>super</code> without arguments.
CYou cannot pass different arguments.
DUse <code>super!</code> keyword.
Explain method overriding in Ruby and how the super keyword works.
Think about how a child class can change a parent's method but still use the parent's version.
You got /4 concepts.
    Write a simple Ruby example showing a superclass method, a subclass overriding it, and using super to call the original method.
    Start with a class Animal and subclass Dog, override speak method.
    You got /5 concepts.