0
0
Rubyprogramming~20 mins

Method overriding in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Method Overriding Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of overridden method in subclass
What is the output of the following Ruby code?
Ruby
class Animal
  def speak
    "Hello from Animal"
  end
end

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

puts Dog.new.speak
AHello from Animal
BRuntimeError
Cnil
DWoof!
Attempts:
2 left
💡 Hint
The subclass method with the same name replaces the parent method.
Predict Output
intermediate
2:00remaining
Calling super in overridden method
What will this Ruby code print?
Ruby
class Parent
  def greet
    "Hi"
  end
end

class Child < Parent
  def greet
    super + ", there!"
  end
end

puts Child.new.greet
Athere!
BHi, there!
CHi
DNoMethodError
Attempts:
2 left
💡 Hint
super calls the parent method's version.
Predict Output
advanced
2:00remaining
Overriding method with different parameters
What is the output of this Ruby code?
Ruby
class Base
  def info(x)
    "Base: #{x}"
  end
end

class Derived < Base
  def info(x, y = nil)
    if y
      "Derived: #{x} and #{y}"
    else
      super(x)
    end
  end
end

puts Derived.new.info(5)
puts Derived.new.info(5, 10)
A
Base: 5
Derived: 5 and 10
B
Derived: 5
Derived: 5 and 10
CArgumentError
D
Base: 5
Base: 5
Attempts:
2 left
💡 Hint
The overridden method uses default parameter and calls super conditionally.
Predict Output
advanced
2:00remaining
Effect of overriding method without calling super
What will this Ruby code output?
Ruby
class Vehicle
  def description
    "Vehicle base description"
  end
end

class Car < Vehicle
  def description
    "Car specific description"
  end
end

puts Vehicle.new.description
puts Car.new.description
A
Vehicle base description
Car specific description
B
Vehicle base description
Vehicle base description
C
Car specific description
Car specific description
DNoMethodError
Attempts:
2 left
💡 Hint
Overriding replaces the parent method unless super is called.
🧠 Conceptual
expert
3:00remaining
Understanding method lookup with overriding and modules
Given this Ruby code, what is the output?
Ruby
module M
  def greet
    "Hello from M"
  end
end

class A
  def greet
    "Hello from A"
  end
end

class B < A
  include M
  def greet
    super + " and B"
  end
end

puts B.new.greet
ANoMethodError
BHello from A and B
CHello from M and B
DHello from B
Attempts:
2 left
💡 Hint
Modules included in a class come before the superclass in method lookup.