0
0
Rubyprogramming~10 mins

Inherited hook 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 define a method that runs when a subclass is created.

Ruby
class Parent
  def self.[1](subclass)
    puts "A new subclass: #{subclass}"
  end
end
Drag options to blanks, or click blank then click option'
Ainherited
Binitialize
Cnew
Dsubclass_created
Attempts:
3 left
💡 Hint
Common Mistakes
Using instance methods like initialize instead of class methods.
Trying to use a method name that does not exist in Ruby hooks.
2fill in blank
medium

Complete the code to call the inherited hook when a subclass is defined.

Ruby
class Parent
  def self.inherited(subclass)
    puts "Subclass created: [1]"
  end
end

class Child < Parent
end
Drag options to blanks, or click blank then click option'
AChild
Bsubclass
Cself
DParent
Attempts:
3 left
💡 Hint
Common Mistakes
Using the class name directly instead of the parameter.
Using self which refers to the parent class.
3fill in blank
hard

Fix the error in the inherited hook to properly call the parent method.

Ruby
class Parent
  def self.inherited(subclass)
    [1]
    puts "Subclass: #{subclass}"
  end
end
Drag options to blanks, or click blank then click option'
Asuper(subclass)
Bsuper()
Csuperclass
Dsuperclass(subclass)
Attempts:
3 left
💡 Hint
Common Mistakes
Calling super without arguments when the parent method expects one.
Using superclass which is not a method call.
4fill in blank
hard

Fill both blanks to create a subclass that triggers the inherited hook and prints its name.

Ruby
class Parent
  def self.inherited(subclass)
    puts "New subclass: [1]"
  end
end

class [2] < Parent
end
Drag options to blanks, or click blank then click option'
Asubclass
BChild
CParent
Dinherited
Attempts:
3 left
💡 Hint
Common Mistakes
Using the parent class name instead of the subclass name.
Not matching the subclass name in the class definition.
5fill in blank
hard

Fill all three blanks to extend the inherited hook to track subclasses in a list.

Ruby
class Parent
  @subclasses = []

  def self.inherited(subclass)
    [1] << [2]
    puts "Tracking subclass: #{subclass}"
  end

  def self.[3]
    @subclasses
  end
end
Drag options to blanks, or click blank then click option'
A@subclasses
Bsubclass
Csubclasses
Dinherited
Attempts:
3 left
💡 Hint
Common Mistakes
Using instance variables instead of class instance variables.
Not defining a method to return the subclasses list.