0
0
Rubyprogramming~20 mins

Custom modules as mixins in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Mixins Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A"Bark"
BRuntimeError
C"Generic sound"
Dnil
Attempts:
2 left
💡 Hint
Remember that methods defined in the class override those from included modules.
🧠 Conceptual
intermediate
1:30remaining
Purpose of using modules as mixins
Why do Ruby programmers use modules as mixins instead of inheritance?
ATo create instances of modules directly
BTo share reusable code across unrelated classes without using inheritance
CTo replace classes entirely
DTo prevent any method overriding
Attempts:
2 left
💡 Hint
Think about code reuse and class relationships.
🔧 Debug
advanced
2: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
ASyntaxError
BTypeError
CNoMethodError: undefined method 'greet' for #<Person:...>
DPrints "Hello!"
Attempts:
2 left
💡 Hint
Check how extend and include differ in Ruby.
📝 Syntax
advanced
1: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
Ainclude Flyable
Bextend Flyable
Cimport Flyable
Duse Flyable
Attempts:
2 left
💡 Hint
Remember the keyword to add instance methods from a module.
🚀 Application
expert
2: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
A"From A"
BRuntimeError
Cnil
D"From B"
Attempts:
2 left
💡 Hint
In Ruby, the last included module's methods override earlier ones.