Challenge - 5 Problems
Ruby Extend Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of extending a module for class methods
What is the output of this Ruby code when the class method
greet is called?Ruby
module Friendly def greet "Hello from module" end end class Person extend Friendly end puts Person.greet
Attempts:
2 left
💡 Hint
Remember that
extend adds module methods as class methods.✗ Incorrect
Using
extend Friendly inside the class adds the module's methods as class methods. So Person.greet calls the module's greet method and returns "Hello from module".❓ Predict Output
intermediate2:00remaining
Effect of including vs extending a module
What will be the output of this Ruby code?
Ruby
module Talk def speak "Speaking" end end class Animal include Talk end class Robot extend Talk end puts Animal.new.speak puts Robot.speak
Attempts:
2 left
💡 Hint
Including adds instance methods; extending adds class methods.
✗ Incorrect
Including
Talk adds speak as an instance method to Animal. Extending Talk adds speak as a class method to Robot. Both calls print "Speaking".🔧 Debug
advanced2:00remaining
Why does this class method call fail?
Given this Ruby code, why does calling
Car.honk raise an error?Ruby
module Sounds def honk "Beep beep!" end end class Car include Sounds end puts Car.honk
Attempts:
2 left
💡 Hint
Think about the difference between
include and extend.✗ Incorrect
Using
include Sounds adds honk as an instance method to Car. Calling Car.honk tries to call a class method, which does not exist, causing a NoMethodError.📝 Syntax
advanced2:00remaining
Identify the syntax error in extending a module
Which option contains a syntax error when trying to add class methods using a module?
Ruby
module Greetings def hello "Hi!" end end class User extend Greetings end
Attempts:
2 left
💡 Hint
Remember how to use
extend with modules.✗ Incorrect
Modules cannot be instantiated with
.new. Option A tries to call Greetings.new, which causes a NoMethodError. The other options correctly extend the module as class methods.🚀 Application
expert3:00remaining
How to add both instance and class methods from a module
You want to add instance methods and class methods from a single module
Features to a class Gadget. Which code correctly achieves this?Ruby
module Features def instance_feature "Instance method" end module ClassMethods def class_feature "Class method" end end end class Gadget # What goes here? end puts Gadget.new.instance_feature puts Gadget.class_feature
Attempts:
2 left
💡 Hint
Use
include for instance methods and extend for class methods.✗ Incorrect
Including
Features adds instance_feature as an instance method. Extending Features::ClassMethods adds class_feature as a class method. This pattern cleanly separates instance and class methods.