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.
array.slice(index)
# OR
array.slice(range)
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.A sub-array of the original array is returned. nil
is returned when the index is out of range.
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 arraysarray1 = [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-arraysa = array1.slice(1) # 2nd elementb = array2.slice(2, 3) # from 3rd element, return 3c = array3.slice(1, 1) # from 2nd element, return only 1d = array4.slice(0, 5) # from 1st element, return all elementse = array5.slice(2) # return 3rd element# print returned valuesputs "#{a}"puts "#{b}"puts "#{c}"puts "#{d}"puts "#{e}"
When the specified index or range is out of bounds, either nothing or nil
is returned. See the example below:
# create an arrayarray = [1, 2, 3, 4, 5]# save retured sub-array after `slice()` calla = array.slice(100) # index out of bound# print value returnedputs "#{a}" # nothing is printed.
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 arrayarray = [1, 2, 3, 4, 5]# use the `slice()` method on arraya = array.slice(-2, 2) # start from the second element backwards# print returned sub-arrayputs "#{a}"