slice!()
methodThe slice!()
method is an array that deletes the element in a specified index position or deletes elements in an array using the specified range.
The returned value is a sub-array of deleted elements of the original array.
array.sort!()
is different from array.sort()
because the latter changes the original array, while array.sort!()
does not.
array.slice!(index)
# OR
array.slice(range)
index
: This is the index position of the element where the deletion should start.
range
: This specifies the position of the element to where deletion starts and the number of elements to delete from there.
This method returns a sub-array of the original array. A nil
or nothing is returned when the index is out of range.
In the example below, several arrays were created and the slice!()
method was called on them.
The deleted elements that are returned are printed to the console.
Lastly, we print the original elements to confirm that slice!()
changes an original array after the method is called on it.
# 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}"# confirm that original arrays have changedputs "#{array1}"puts "#{array2}"puts "#{array3}"puts "#{array4}"puts "#{array5}"