Challenge - 5 Problems
Ruby Mixins Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a class using a module mixin
What is the output of this Ruby code when the
Dog object calls sound?Ruby
module AnimalSounds def sound "Generic sound" end end class Dog include AnimalSounds def sound "Bark" end end puts Dog.new.sound
Attempts:
2 left
💡 Hint
Remember that methods defined in the class override those from included modules.
✗ Incorrect
The
Dog class includes the AnimalSounds module, but it also defines its own sound method. The class method overrides the module method, so calling sound on a Dog instance returns "Bark".🧠 Conceptual
intermediate1:30remaining
Purpose of using modules as mixins
Why do Ruby programmers use modules as mixins instead of inheritance?
Attempts:
2 left
💡 Hint
Think about code reuse and class relationships.
✗ Incorrect
Modules as mixins allow sharing methods across different classes that do not share a parent-child relationship. This avoids the limitations of single inheritance and promotes code reuse.
🔧 Debug
advanced2:00remaining
Identify the error in module mixin usage
What error will this Ruby code produce?
Ruby
module Greetings def greet "Hello!" end end class Person extend Greetings end puts Person.new.greet
Attempts:
2 left
💡 Hint
Check how
extend and include differ in Ruby.✗ Incorrect
Using
extend Greetings adds the module methods as class methods, not instance methods. Since greet is called on an instance, it raises a NoMethodError.📝 Syntax
advanced1:30remaining
Correct syntax to include a module as a mixin
Which option correctly includes the
Flyable module as a mixin in the Bird class?Ruby
module Flyable def fly "I can fly!" end end class Bird # Which line correctly mixes in Flyable? end
Attempts:
2 left
💡 Hint
Remember the keyword to add instance methods from a module.
✗ Incorrect
The
include keyword mixes in module methods as instance methods. extend adds them as class methods. import and use are not Ruby keywords.🚀 Application
expert2:30remaining
Predict the output with multiple mixins and method lookup
What will this Ruby code print?
Ruby
module A def message "From A" end end module B def message "From B" end end class C include A include B end puts C.new.message
Attempts:
2 left
💡 Hint
In Ruby, the last included module's methods override earlier ones.
✗ Incorrect
When multiple modules are included, Ruby uses the method from the last included module. Here,
B is included after A, so message from B is called.