Bird
0
0

Given this Ruby code using a hook pattern:

medium📝 Predict Output Q13 of 15
Ruby - Advanced Metaprogramming
Given this Ruby code using a hook pattern:
class Framework
  def self.before_save(&block)
    @before_save_hook = block
  end

  def save
    self.class.instance_variable_get(:@before_save_hook)&.call
    puts 'Saving data'
  end
end

class User < Framework
  before_save { puts 'Validate user' }
end

User.new.save

What is the output when User.new.save is called?
AValidate user Saving data
BSaving data
CNoMethodError
DValidate user
Step-by-Step Solution
Solution:
  1. Step 1: Understand the hook registration

    The before_save class method stores a block in @before_save_hook for the User class.
  2. Step 2: Analyze the save method call

    When save is called, it calls the stored hook block (prints 'Validate user') then prints 'Saving data'.
  3. Final Answer:

    Validate user Saving data -> Option A
  4. Quick Check:

    Hook runs before save message = B [OK]
Quick Trick: Hook block runs before main save output [OK]
Common Mistakes:
  • Ignoring the hook call in save method
  • Expecting only 'Saving data' output
  • Confusing instance and class variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes