How to Use the Ruby slice Method

09/25/2021

Contents

In this article, you will learn how to use the Ruby slice method.

Using the slice method

The slice method in Ruby is used to extract a specific portion of a string or an array. This method can be used to extract a substring or a subarray from a given string or array based on the starting and ending indices.

Here is an overview of how to use the slice method in Ruby:

Using the slice method with a String

The slice method can be used with a string to extract a specific portion of the string. The syntax for using the slice method with a string is as follows:

string.slice(start_index, length)

Here, start_index is the index from where the substring extraction should start, and length is the number of characters to extract. If the length parameter is not provided, then the slice method will extract all the characters from the starting index to the end of the string.

Example:

string = "Hello, World!"
puts string.slice(0, 5)    #=> "Hello"
puts string.slice(7, 5)    #=> "World"

Using the slice method with an Array

The slice method can also be used with an array to extract a specific portion of the array. The syntax for using the slice method with an array is as follows:

array.slice(start_index, length)

Here, start_index is the index from where the subarray extraction should start, and length is the number of elements to extract. If the length parameter is not provided, then the slice method will extract all the elements from the starting index to the end of the array.

Example:

array = [1, 2, 3, 4, 5]
puts array.slice(0, 2)     #=> [1, 2]
puts array.slice(3, 2)     #=> [4, 5]

Using the slice method with a Range

The slice method can also be used with a range to extract a specific portion of a string or an array. The syntax for using the slice method with a range is as follows:

object.slice(range)

Here, range is the range of indices or elements to extract. If the range parameter is not provided, then the slice method will extract all the elements from the starting index to the end of the object.

Example:

string = "Hello, World!"
puts string.slice(0..4)    #=> "Hello"
puts string.slice(7..11)   #=> "World"

array = [1, 2, 3, 4, 5]
puts array.slice(0..1)     #=> [1, 2]
puts array.slice(3..4)     #=> [4, 5]

Using the shorthand [] syntax

The slice method can also be invoked using the shorthand [] syntax in Ruby. The syntax for using the shorthand [] syntax is as follows:

object[start_index, length]
object[range]

Example:

string = "Hello, World!"
puts string[0, 5]    #=> "Hello"
puts string[7, 5]    #=> "World"
puts string[0..4]    #=> "Hello"
puts string[7..11]   #=> "World"

array = [1, 2