What is slice!() in Ruby?

The slice!() method

The 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.

Syntax


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

Parameters

  • 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.

Return value

This method returns a sub-array of the original array. A nil or nothing is returned when the index is out of range.

Code

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 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}"
# confirm that original arrays have changed
puts "#{array1}"
puts "#{array2}"
puts "#{array3}"
puts "#{array4}"
puts "#{array5}"

Free Resources