Challenge - 5 Problems
Ruby Modules Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of including modules in Ruby
What is the output of this Ruby code when calling
obj.greet?Ruby
module A def greet "Hello from A" end end module B def greet "Hello from B" end end class MyClass include A include B end obj = MyClass.new puts obj.greet
Attempts:
2 left
💡 Hint
Remember that the last included module's methods override earlier ones.
✗ Incorrect
In Ruby, when multiple modules are included, the methods from the last included module take precedence. Here, module B is included after A, so its greet method overrides A's.
🧠 Conceptual
intermediate1:30remaining
Why Ruby uses modules instead of multiple inheritance
Why does Ruby use modules to solve the problem of multiple inheritance instead of allowing classes to inherit from multiple classes?
Attempts:
2 left
💡 Hint
Think about method conflicts and complexity in multiple inheritance.
✗ Incorrect
Ruby uses modules to share reusable code across classes without the complexity and ambiguity of multiple inheritance, such as the diamond problem. Modules provide a clean way to mix in behavior.
🔧 Debug
advanced1:30remaining
Identify the error in module inclusion
What error will this Ruby code produce and why?
Ruby
module M def hello "Hi" end end class C include M include M end c = C.new puts c.hello
Attempts:
2 left
💡 Hint
Including the same module twice is allowed but has no extra effect.
✗ Incorrect
Including the same module multiple times does not cause an error in Ruby. The method is available and outputs "Hi".
❓ Predict Output
advanced2:00remaining
Method lookup order with modules and inheritance
What is the output of this Ruby code?
Ruby
module M1 def speak "M1 speaks" end end module M2 def speak "M2 speaks" end end class Parent def speak "Parent speaks" end end class Child < Parent include M1 include M2 end puts Child.new.speak
Attempts:
2 left
💡 Hint
Modules included last override earlier modules and superclass methods.
✗ Incorrect
Ruby's method lookup checks the last included module first, then earlier modules, then superclass. Here, M2 is last included, so its speak method is called.
🧠 Conceptual
expert2:30remaining
How modules solve the diamond problem in Ruby
In multiple inheritance, the diamond problem occurs when a class inherits from two classes that both inherit from a common superclass. How do Ruby modules help avoid this problem?
Attempts:
2 left
💡 Hint
Think about how Ruby searches for methods when modules are included.
✗ Incorrect
Ruby solves the diamond problem by inserting modules into the inheritance chain in a linear order. The method lookup path checks included modules in reverse order of inclusion before moving to the superclass, avoiding ambiguity.