Bird
0
0

You want to create multiple methods dynamically that remember different greetings. Which code correctly uses define_method with closures to achieve this?

hard📝 Application Q8 of 15
Ruby - Advanced Metaprogramming
You want to create multiple methods dynamically that remember different greetings. Which code correctly uses define_method with closures to achieve this?
class MultiGreeter
  def initialize(greetings)
    greetings.each do |key, phrase|
      # fill in here
    end
  end
end

mg = MultiGreeter.new({hello: 'Hi', bye: 'Goodbye'})
puts mg.hello
puts mg.bye
Adefine_method(key) { phrase }
Bdefine_method(key) { puts phrase }
Cdefine_method(:key) { phrase }
Ddefine_method(key) { puts key }
Step-by-Step Solution
Solution:
  1. Step 1: Understand dynamic method creation with closures

    Each method should return the phrase string stored in the closure.
  2. Step 2: Check each option

    define_method(key) { phrase } correctly defines method named by key returning phrase. define_method(key) { puts phrase } prints phrase but returns nil. define_method(:key) { phrase } uses symbol :key literally, not variable. define_method(key) { puts key } returns key, not phrase.
  3. Final Answer:

    define_method(key) { phrase } -> Option A
  4. Quick Check:

    Use variable key and phrase in define_method block [OK]
Quick Trick: Use variables directly inside define_method block for closures [OK]
Common Mistakes:
  • Using symbol literal instead of variable
  • Using puts inside block returning nil
  • Returning wrong variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes