0
0
Rubyprogramming~20 mins

Module methods in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Module Methods Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
AHello from module!
BNoMethodError
Cnil
DSyntaxError
Attempts:
2 left
💡 Hint
Look at how the method is defined with self. It means it belongs to the module itself.
Predict Output
intermediate
2: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
ATools module info
BNoMethodError
Cnil
DSyntaxError
Attempts:
2 left
💡 Hint
Including a module adds instance methods, but module methods are not included as class methods.
🔧 Debug
advanced
3: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)
AChange MathHelpers.square to def square(x) without self
BAdd include MathHelpers inside Calculator
CChange Calculator.square to call MathHelpers.square(x)
DChange Calculator.square to an instance method
Attempts:
2 left
💡 Hint
Module methods with self need to be called with the module name.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in module method definition
Which option shows the correct way to define a module method in Ruby?
A
module M
  def method:
    puts 'Hi'
  end
end
B
module M
  def method(self)
    puts 'Hi'
  end
end
C
module M
  def method.self
    puts 'Hi'
  end
end
D
module M
  def self.method
    puts 'Hi'
  end
end
Attempts:
2 left
💡 Hint
Module methods use self. before the method name.
🚀 Application
expert
3: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)
Amethods: 0, instance_methods: 1
Bmethods: 1, instance_methods: 1
Cmethods: 1, instance_methods: 0
Dmethods: 0, instance_methods: 0
Attempts:
2 left
💡 Hint
Including a module adds instance methods, but not module methods as class methods.