Bird
0
0

What will this Ruby code print?

medium📝 Predict Output Q5 of 15
Ruby - Metaprogramming Fundamentals
What will this Ruby code print?
class Test
  [:a, :b].each do |name|
    define_method(name) { name.to_s.upcase }
  end
end

t = Test.new
puts t.a + t.b
ANoMethodError
BAB
Ca b
Dab
Step-by-Step Solution
Solution:
  1. Step 1: Analyze method definitions

    Methods :a and :b are defined to return their symbol name as uppercase strings.
  2. Step 2: Check output of method calls

    Calling t.a returns "A", t.b returns "B", so concatenating prints "AB".
  3. Final Answer:

    AB -> Option B
  4. Quick Check:

    Dynamic methods return uppercase names = AB [OK]
Quick Trick: Symbols can be converted to uppercase strings with to_s.upcase [OK]
Common Mistakes:
  • Expecting lowercase output
  • Forgetting to call methods on instance
  • Assuming NoMethodError due to dynamic methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes