Bird
0
0

What will be the output of this Ruby code?

hard📝 Application Q9 of 15
Ruby - Methods
What will be the output of this Ruby code?
def merge_and_sort(*arrays)
  arrays.flatten.sort
end

p merge_and_sort([5, 3], [1, 4], [2])
A[5, 3, 1, 4, 2]
B[[5, 3], [1, 4], [2]]
C[1, 2, 3, 4, 5]
D[1, 3, 4, 5]
Step-by-Step Solution
Solution:
  1. Step 1: Understand the method

    The method accepts any number of arrays, flattens them into one array, then sorts the elements.
  2. Step 2: Flatten the arrays

    Input arrays: [5, 3], [1, 4], [2] flatten to [5, 3, 1, 4, 2].
  3. Step 3: Sort the flattened array

    Sorted array is [1, 2, 3, 4, 5].
  4. Final Answer:

    [1, 2, 3, 4, 5] -> Option C
  5. Quick Check:

    Flatten then sort arrays [OK]
Quick Trick: Flatten arrays before sorting to combine elements [OK]
Common Mistakes:
MISTAKES
  • Not flattening arrays before sorting
  • Expecting nested arrays as output
  • Misordering elements after sort

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes