Bird
0
0

What will this Ruby code output?

medium📝 Predict Output Q4 of 15
Ruby - Advanced Metaprogramming
What will this Ruby code output?
class Framework
  def self.before_save(&block)
    @before_save = block
  end

  def self.run_before_save
    @before_save.call if @before_save
  end
end

Framework.before_save { puts 'Saving...'}
Framework.run_before_save
AError: no block given
BNo output
CError: undefined method call
DSaving...
Step-by-Step Solution
Solution:
  1. Step 1: Understand hook assignment and call

    The before_save method stores a block in @before_save. run_before_save calls this block if set.
  2. Step 2: Trace the code execution

    We assign a block that prints 'Saving...'. Then run_before_save calls it, printing the message.
  3. Final Answer:

    Saving... -> Option D
  4. Quick Check:

    Hook block called = A [OK]
Quick Trick: Stored blocks run when called explicitly [OK]
Common Mistakes:
  • Assuming no output without explicit call
  • Confusing block storage with immediate execution
  • Expecting errors without block checks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes