Bird
0
0

What will this Ruby code output?

medium📝 Predict Output Q5 of 15
Ruby - Functional Patterns in Ruby
What will this Ruby code output?
class Greeter
  def greet(name)
    "Hello, #{name}!"
  end
end

greet_lambda = ->(name) { "Hi, #{name}!" }

g = Greeter.new
puts g.greet("Alice")
puts greet_lambda.call("Bob")
AHello, Alice! Hello, Bob!
BHi, Alice! Hello, Bob!
CHello, Alice! Hi, Bob!
DHi, Alice! Hi, Bob!
Step-by-Step Solution
Solution:
  1. Step 1: Identify outputs of greet method and lambda

    g.greet("Alice") returns "Hello, Alice!"; greet_lambda.call("Bob") returns "Hi, Bob!".
  2. Step 2: Confirm output order

    First puts prints greet result, second puts prints lambda result.
  3. Final Answer:

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

    Method and lambda outputs combined = Hello, Alice! and Hi, Bob! [OK]
Quick Trick: Method and lambda produce different greetings [OK]
Common Mistakes:
  • Mixing up which greeting belongs to method or lambda
  • Forgetting to call lambda with .call
  • Assuming both greetings are the same

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes