0
0
Rubyprogramming~10 mins

Method lookup chain 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 call the method defined in the class.

Ruby
class Animal
  def speak
    'Hello'
  end
end

animal = Animal.new
puts animal.[1]
Drag options to blanks, or click blank then click option'
Aspeak
Brun
Cjump
Dtalk
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call a method that does not exist in the class.
Using a wrong method name.
2fill in blank
medium

Complete the code to call the method from the module included in the class.

Ruby
module Talk
  def speak
    'Hi from module'
  end
end

class Person
  include Talk
end

p = Person.new
puts p.[1]
Drag options to blanks, or click blank then click option'
Arun
Bspeak
Cjump
Dtalk
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a method not defined in the module or class.
Confusing module methods with class methods.
3fill in blank
hard

Fix the error by completing the code to call the method from the superclass.

Ruby
class Vehicle
  def start
    'Starting engine'
  end
end

class Car < Vehicle
end

car = Car.new
puts car.[1]
Drag options to blanks, or click blank then click option'
Adrive
Bpark
Cstop
Dstart
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call a method not defined in the class or its ancestors.
Using a method name that does not exist.
4fill in blank
hard

Fill both blanks to complete the method lookup chain with module and superclass methods.

Ruby
module M
  def greet
    'Hello from M'
  end
end

class A
  def greet
    'Hello from A'
  end
end

class B < A
  include M
end

b = B.new
puts b.[1]
puts b.class.superclass.instance_method(:[2]).bind(b).call if b.class.superclass.method_defined?(:[2])
Drag options to blanks, or click blank then click option'
Agreet
Bstart
Crun
Dspeak
Attempts:
3 left
💡 Hint
Common Mistakes
Using different method names for the two blanks.
Not matching the method name in the superclass call.
5fill in blank
hard

Fill all three blanks to complete the method lookup chain with class, module, and superclass methods.

Ruby
module M1
  def action
    'Action from M1'
  end
end

module M2
  def action
    'Action from M2'
  end
end

class Parent
  def action
    'Action from Parent'
  end
end

class Child < Parent
  include M1
  include M2

  def action
    'Action from Child'
  end
end

c = Child.new
puts c.[1]
puts c.singleton_class.ancestors[2].instance_method(:action).bind(c).call
puts c.class.superclass.instance_method(:[2]).bind(c).call if c.class.superclass.method_defined?(:[3])
Drag options to blanks, or click blank then click option'
Aaction
Dstart
Attempts:
3 left
💡 Hint
Common Mistakes
Using different method names for blanks.
Confusing the order of method lookup.