How to Slice an Array in Ruby: Syntax and Examples
In Ruby, you can slice an array using
array[start, length] or array[range]. The start is the index where slicing begins, and length is how many elements to take. Using a range like array[1..3] slices from index 1 to 3 inclusive.Syntax
You can slice an array in Ruby using two main ways:
array[start, length]: Extractslengthelements starting from indexstart.array[range]: Extracts elements within the given range of indices.
Indices start at 0. Negative indices count from the end (-1 is last element).
ruby
array = [10, 20, 30, 40, 50] slice1 = array[1, 3] # From index 1, take 3 elements slice2 = array[2..4] # From index 2 to 4 inclusive
Example
This example shows how to slice an array using both start, length and range syntax.
ruby
array = ['a', 'b', 'c', 'd', 'e'] slice1 = array[1, 3] slice2 = array[2..4] puts "Slice with start,length: #{slice1.inspect}" puts "Slice with range: #{slice2.inspect}"
Output
Slice with start,length: ["b", "c", "d"]
Slice with range: ["c", "d", "e"]
Common Pitfalls
Common mistakes when slicing arrays in Ruby include:
- Using a negative length, which returns
nil. - Confusing
array[start, length]witharray[start..end]ranges. - Expecting slicing to modify the original array (it returns a new array).
ruby
array = [1, 2, 3, 4, 5] wrong_slice = array[1, -2] # Returns nil correct_slice = array[1..-2] # Returns elements from index 1 to second last puts wrong_slice.inspect puts correct_slice.inspect
Output
nil
[2, 3, 4]
Quick Reference
| Syntax | Description | Example |
|---|---|---|
| array[start, length] | Slice from index start, length elements | array[2, 3] => elements at 2,3,4 |
| array[range] | Slice elements within index range | array[1..3] => elements at 1,2,3 |
| array[start..-1] | Slice from start to end | array[2..-1] => from index 2 to last |
| array[-3, 2] | Slice using negative start index | array[-3, 2] => 3rd last and next element |
Key Takeaways
Use array[start, length] to slice a specific number of elements from a start index.
Use array[range] to slice elements between two indices inclusive.
Negative indices count from the end of the array.
Slicing returns a new array and does not change the original.
Avoid negative length values; they return nil.