What is array.slice() in Ruby?

The array.slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.

Syntax

array.slice(index)
# OR
array.slice(range)

Parameters

The slice() method accepts two possible arguments.

  • index: The position from which to return an array of elements.
  • range: Specifying the starting position and the number of elements to return from that position.

Return value

A sub-array of the original array is returned. nil is returned when the index is out of range.

Code

Example 1

In the example below, we will create arrays and use the slice() method to return sub-arrays of the original arrays we created. Then, we display it on the console.

# create arrays
array1 = [1, 2, 3, 4, 5]
array2 = ["a", "b", "c", "d", "e"]
array3 = ["cat", "dog", "cow", "rat", "fox"]
array4 = [true, false, nil]
array5 = ["", "nil", "false", "true"]
# call `slice()` method and save returned sub-arrays
a = array1.slice(1) # 2nd element
b = array2.slice(2, 3) # from 3rd element, return 3
c = array3.slice(1, 1) # from 2nd element, return only 1
d = array4.slice(0, 5) # from 1st element, return all elements
e = array5.slice(2) # return 3rd element
# print returned values
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
puts "#{e}"

Example 2

When the specified index or range is out of bounds, either nothing or nil is returned. See the example below:

# create an array
array = [1, 2, 3, 4, 5]
# save retured sub-array after `slice()` call
a = array.slice(100) # index out of bound
# print value returned
puts "#{a}" # nothing is printed.

Example 3

Note that a negative index counts backward. This means that the position of elements is counted backward. Hence, -1 is the last element in the array.

In the example below, the subarray starts from the second-last element of the array, and the same method is used to get the other elements.

# create an array
array = [1, 2, 3, 4, 5]
# use the `slice()` method on array
a = array.slice(-2, 2) # start from the second element backwards
# print returned sub-array
puts "#{a}"

Free Resources