Bird
0
0

Find the bug in this Ruby code:

medium📝 Debug Q7 of 15
Ruby - Arrays
Find the bug in this Ruby code:
arr = [10, 5, 8]
sorted = arr.sort.reverse!
p sorted
Ap sorted should be p arr
Breverse! cannot be called on the result of sort
Csort does not return a new array
Dreverse! modifies arr, not sorted
Step-by-Step Solution
Solution:
  1. Step 1: Understand method chaining with reverse!

    sort returns a new array, and reverse! modifies an array in place and returns it.
  2. Step 2: Check if reverse! can be called on sort result

    reverse! can be called on the new array, so no error here. The code works correctly.
  3. Step 3: Identify the actual bug

    There is no bug calling reverse! on sort result. The code works correctly.
  4. Final Answer:

    None of the options correctly describe a bug -> Option B (closest but no bug)
  5. Quick Check:

    reverse! can be called on sort result [OK]
Quick Trick: reverse! modifies array in place, can chain after sort [OK]
Common Mistakes:
  • Thinking reverse! can't chain after sort
  • Confusing sort and sort!
  • Misunderstanding method chaining

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes