Challenge - 5 Problems
Module Methods Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of calling a module method directly
What is the output of this Ruby code?
Ruby
module Greetings def self.say_hello "Hello from module!" end end puts Greetings.say_hello
Attempts:
2 left
💡 Hint
Look at how the method is defined with self. It means it belongs to the module itself.
✗ Incorrect
The method say_hello is defined as a module method using self. It can be called directly on the module name. So it prints the string.
❓ Predict Output
intermediate2:00remaining
Output of including a module with a module method
What happens when you include a module with a module method and call that method on the including class?
Ruby
module Tools def self.info "Tools module info" end end class Machine include Tools end puts Machine.info
Attempts:
2 left
💡 Hint
Including a module adds instance methods, but module methods are not included as class methods.
✗ Incorrect
Including a module adds its instance methods to the class. But module methods defined with self are not included. So Machine.info is undefined and raises NoMethodError.
🔧 Debug
advanced3:00remaining
Fix the code to call a module method from a class
This code tries to call a module method from a class method but raises an error. Which option fixes it?
Ruby
module MathHelpers def self.square(x) x * x end end class Calculator def self.square(x) square(x) end end puts Calculator.square(4)
Attempts:
2 left
💡 Hint
Module methods with self need to be called with the module name.
✗ Incorrect
The Calculator class method tries to call square(x) but no such method exists in Calculator. Calling MathHelpers.square(x) fixes the error.
📝 Syntax
advanced2:00remaining
Identify the syntax error in module method definition
Which option shows the correct way to define a module method in Ruby?
Attempts:
2 left
💡 Hint
Module methods use self. before the method name.
✗ Incorrect
Option D correctly defines a module method using def self.method. Other options have invalid syntax.
🚀 Application
expert3:00remaining
How many methods does this module add to a class?
Given this module and class, how many methods does the class have after including the module?
Ruby
module Features def self.module_method 'module method' end def instance_method 'instance method' end end class Product include Features end methods = Product.methods - Object.methods instance_methods = Product.instance_methods(false)
Attempts:
2 left
💡 Hint
Including a module adds instance methods, but not module methods as class methods.
✗ Incorrect
The module method defined with self is not added to the class methods. The instance_method is added as an instance method. So Product.methods - Object.methods is empty (0), and Product.instance_methods(false) includes :instance_method (1).