Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Methods
What will be the output of this Ruby code?
def greet_all(*names)
  names.map { |name| "Hello, #{name}!" }
end

p greet_all('Alice', 'Bob')
Anil
B"Hello, Alice! Hello, Bob!"
CError: undefined method 'map' for Array
D["Hello, Alice!", "Hello, Bob!"]
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the method behavior

    The method collects all names into an array and uses map to create a new array with greetings.
  2. Step 2: Evaluate the output

    Calling greet_all('Alice', 'Bob') returns an array with two greeting strings.
  3. Final Answer:

    ["Hello, Alice!", "Hello, Bob!"] -> Option D
  4. Quick Check:

    map transforms each element in *args array [OK]
Quick Trick: Use map on *args array to transform each argument [OK]
Common Mistakes:
  • Expecting a single string instead of array
  • Confusing map with join
  • Assuming map is undefined for arrays

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes