0
0
Rubyprogramming~10 mins

Method overriding in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to override the method greet in the subclass.

Ruby
class Parent
  def greet
    puts "Hello from Parent"
  end
end

class Child < Parent
  def [1]
    puts "Hello from Child"
  end
end

child = Child.new
child.greet
Drag options to blanks, or click blank then click option'
Agreeting
Bhello
Cgreet
Dsay_hello
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name in the subclass so it doesn't override.
Forgetting to define the method in the subclass.
2fill in blank
medium

Complete the code to call the parent class method greet inside the overridden method.

Ruby
class Parent
  def greet
    puts "Hello from Parent"
  end
end

class Child < Parent
  def greet
    [1]
    puts "Hello from Child"
  end
end

child = Child.new
child.greet
Drag options to blanks, or click blank then click option'
Asuper
Bsuper.greet
CParent.greet
Dself.greet
Attempts:
3 left
💡 Hint
Common Mistakes
Calling super.greet which is invalid syntax in Ruby.
Calling Parent.greet which is a class method call, not instance method.
3fill in blank
hard

Fix the error in the code by correctly overriding the method info.

Ruby
class Animal
  def info
    puts "I am an animal"
  end
end

class Dog < Animal
  def [1]
    puts "I am a dog"
  end
end

dog = Dog.new
dog.info
Drag options to blanks, or click blank then click option'
AInfo
Binfo
Cinformation
Ddetails
Attempts:
3 left
💡 Hint
Common Mistakes
Using capitalized method name Info which does not override.
Using a different method name that does not match the parent.
4fill in blank
hard

Fill both blanks to override the method describe and call the parent method inside it.

Ruby
class Vehicle
  def describe
    puts "This is a vehicle"
  end
end

class Car < Vehicle
  def [1]
    [2]
    puts "This is a car"
  end
end

car = Car.new
car.describe
Drag options to blanks, or click blank then click option'
Adescribe
Bsuper
Csuper.describe
Ddescription
Attempts:
3 left
💡 Hint
Common Mistakes
Using super.describe which is invalid syntax.
Using a different method name so the parent method is not overridden.
5fill in blank
hard

Fill all three blanks to override display, call the parent method, and add extra output.

Ruby
class Computer
  def display
    puts "Display from Computer"
  end
end

class Laptop < Computer
  def [1]
    [2]
    puts [3]
  end
end

laptop = Laptop.new
laptop.display
Drag options to blanks, or click blank then click option'
Adisplay
Bsuper
C"Display from Laptop"
Dshow
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name so override does not happen.
Calling super.display which is invalid.
Not printing the extra message correctly.