Bird
0
0

Identify the error in the following Ruby code:

medium📝 Debug Q6 of 15
Ruby - Arrays
Identify the error in the following Ruby code:
arr = [1, 2, 3, 4, 5]
slice = arr[3..1]
puts slice.inspect
AThe range 3..1 is invalid and returns nil
BThe code raises a runtime error
CThe range 3..1 returns an empty array
DThe code returns elements from index 3 to 1
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the range 3..1

    The start index 3 is greater than the end index 1, so the range is empty.
  2. Step 2: Check Ruby behavior for empty ranges in slicing

    Ruby returns an empty array when the range is empty.
  3. Final Answer:

    The range 3..1 returns an empty array -> Option C
  4. Quick Check:

    Invalid range returns empty array, not nil or error [OK]
Quick Trick: Ranges with start > end return empty array in slicing [OK]
Common Mistakes:
  • Expecting nil instead of empty array
  • Expecting runtime error
  • Assuming reversed range returns elements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes