Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Methods
What will be the output of the following Ruby code?
def greet(name)
  "Hello, #{name}!"
  42
end

puts greet("Alice")
A"Hello, Alice!"
Bnil
C42
DSyntaxError
Step-by-Step Solution
Solution:
  1. Step 1: Analyze method body lines

    The method has two lines: first creates a string but does not return it explicitly; second line is the number 42.
  2. Step 2: Identify returned value

    Ruby returns the last evaluated expression, which is 42.
  3. Final Answer:

    42 -> Option C
  4. Quick Check:

    Last line value returned = 42 [OK]
Quick Trick: Method returns last line value, not earlier lines [OK]
Common Mistakes:
  • Assuming first string line is returned
  • Confusing puts output with return value
  • Expecting nil because no explicit return

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes