Bird
0
0

Given the following code, what will be the output?

hard📝 Application Q15 of 15
Ruby - Blocks, Procs, and Lambdas
Given the following code, what will be the output?
class Greeter
  def initialize(name)
    @name = name
  end
  def greet
    "Hello, #{@name}!"
  end
end

g1 = Greeter.new("Bob")
g2 = Greeter.new("Sue")
m1 = g1.method(:greet)
m2 = g2.method(:greet)

puts m1.call
puts m2.call
AHello, Sue!\nHello, Sue!
BHello, Bob!\nHello, Bob!
CHello, Bob!\nHello, Sue!
DError: undefined method greet
Step-by-Step Solution
Solution:
  1. Step 1: Understand instance variables and method objects

    Each Greeter instance stores its own @name. The method(:greet) returns a Method object bound to that instance.
  2. Step 2: Calling Method objects

    Calling m1.call runs greet on g1, printing "Hello, Bob!". Similarly, m2.call prints "Hello, Sue!".
  3. Final Answer:

    Hello, Bob! Hello, Sue! -> Option C
  4. Quick Check:

    Method objects keep instance context [OK]
Quick Trick: Method objects remember their object, so output matches instance data [OK]
Common Mistakes:
  • Assuming method objects lose instance context
  • Expecting same output for both calls
  • Confusing method object with class method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes