0
0
Rubyprogramming~20 mins

Method lookup chain in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Method Lookup Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Method lookup with modules and classes
What is the output of this Ruby code?
Ruby
module A
  def greet
    "Hello from A"
  end
end

module B
  def greet
    "Hello from B"
  end
end

class C
  include A
  include B
end

puts C.new.greet
AHello from B
BHello from A
CNoMethodError
DHello from C
Attempts:
2 left
💡 Hint
Remember that the last included module takes precedence in Ruby's method lookup chain.
🧠 Conceptual
intermediate
2:00remaining
Understanding method lookup order with inheritance and modules
Given a class that inherits from a superclass and includes a module, which order does Ruby follow to find a method?
A1, 2, 3, 4
B1, 3, 2, 4
C2, 1, 3, 4
D3, 4, 1, 2
Attempts:
2 left
💡 Hint
Think about where Ruby looks first: the class, then modules included in it, then the superclass and its modules.
Predict Output
advanced
2:00remaining
Method lookup with prepend and include
What will this Ruby code print?
Ruby
module M
  def hello
    "Hello from M"
  end
end

class X
  include M
  def hello
    "Hello from X"
  end
end

class Y < X
  prepend M
end

puts Y.new.hello
AHello from Y
BHello from X
CHello from M
DNoMethodError
Attempts:
2 left
💡 Hint
Remember that prepend puts the module before the class in the lookup chain.
Predict Output
advanced
2:00remaining
Method lookup with super and modules
What is the output of this Ruby code?
Ruby
module M
  def foo
    "foo from M"
  end
end

class A
  include M
end

class B < A
  def foo
    super + " and foo from B"
  end
end

obj = B.new
puts obj.foo
A" and foo from B"
B"foo from M"
CNoMethodError
D"foo from M and foo from B"
Attempts:
2 left
💡 Hint
Remember that super starts method lookup from the superclass and follows its full ancestor chain, including modules included there.
Predict Output
expert
3:00remaining
Complex method lookup with multiple modules and prepend
What is the output of this Ruby code?
Ruby
module M1
  def call
    "M1"
  end
end

module M2
  def call
    "M2"
  end
end

class Base
  def call
    "Base"
  end
end

class Derived < Base
  include M1
  prepend M2
end

puts Derived.new.call
AM1
BM2
CBase
DNoMethodError
Attempts:
2 left
💡 Hint
Prepend modules come before the class in lookup order, even if the class includes other modules.