Bird
0
0

Which of the following is the correct syntax to slice the first 4 elements from an array arr in Ruby?

easy📝 Syntax Q3 of 15
Ruby - Arrays
Which of the following is the correct syntax to slice the first 4 elements from an array arr in Ruby?
Aarr[1..4]
Barr[0...4]
Carr[0..4]
Darr[1...5]
Step-by-Step Solution
Solution:
  1. Step 1: Identify indices for first 4 elements

    Indices start at 0, so first 4 elements are at indices 0, 1, 2, 3.
  2. Step 2: Choose range that includes indices 0 to 3

    arr[0...4] excludes index 4, selecting indices 0, 1, 2, 3 exactly.
  3. Final Answer:

    arr[0...4] -> Option B
  4. Quick Check:

    Use 0...4 to get first 4 elements (indices 0 to 3) [OK]
Quick Trick: Use 0...n to get first n elements [OK]
Common Mistakes:
  • Starting index at 1 instead of 0
  • Using .. which includes one extra element
  • Confusing inclusive and exclusive ranges

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes