Bird
0
0

Given this module:

hard📝 Application Q9 of 15
Ruby - Modules and Mixins
Given this module:
module Formatter
  def self.format_name(first, last)
    "#{last}, #{first}".upcase
  end
end

How can you use format_name inside a class Person without repeating the module name every time?
AUse <code>extend Formatter</code> inside the class and call <code>format_name</code> directly
BDefine an instance method that calls <code>Formatter.format_name</code>
CAssign <code>format_name</code> to a local variable
DUse <code>include Formatter</code> inside the class and call <code>format_name</code> directly
Step-by-Step Solution
Solution:
  1. Step 1: Understand method type

    format_name is a module method (self method), not an instance method.
  2. Step 2: Analyze extend vs include

    extend Formatter adds module's instance methods as class methods to Person, but format_name is not an instance method of Formatter; include Formatter adds instance methods to Person instances.
  3. Step 3: Use wrapper instance method

    Defining an instance method in Person that calls Formatter.format_name allows calling it without repeating module name externally.
  4. Final Answer:

    Define an instance method that calls Formatter.format_name -> Option B
  5. Quick Check:

    Module methods require explicit calls or wrappers = D [OK]
Quick Trick: Wrap module methods in instance methods to avoid repeating module name [OK]
Common Mistakes:
  • Expecting extend to import module methods as instance methods
  • Using include to import module methods
  • Trying to assign method to variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes