Array slice function in Ruby

RubyServer Side ProgrammingProgramming

Sometimes we may want to exact a portion from an array data and perform some operation on it. In Ruby, we can do that with the help of the slice() function that takes two arguments, both of them indices, that are used to define a subsequence which then can be extracted from the array.

Syntax

The syntax of the slice() function is shown below −

res = Array.slice(x,y)

Here, x and y denote the starting index and the ending index, respectively.

Example 1

Now that we know a little about the slice() function on arrays, let's take a couple of examples and see how to use it in a program. Consider the code shown below.

# declaring the arrays
first_arr = [18, 22, 34, nil, 7, 6]
second_arr = [1, 4, 3, 1, 88, 9]
third_arr = [18, 23, 50, 6]

# slice method example
puts "slice() method result : #{first_arr.slice(2, 4)}\n"
puts "slice() method result : #{second_arr.slice(1, 3)}\n"
puts "slice() method result : #{third_arr.slice(2, 3)}\n"

Output

When we execute this code, it will produce the following output −

slice() method result : [34, nil, 7, 6]
slice() method result : [4, 3, 1]
slice() method result : [50, 6]

Example 2

Let's take another example. Here, instead of integer values, we will take arrays of strings. Consider the code shown below.

# declaring array
first_arr = ["abc", "nil", "dog"]
second_arr = ["cat", nil]
third_arr = ["cow", nil, "dog"]

# slice method example
puts "slice() method result : #{first_arr.slice(1, 3)}\n"
puts "slice() method result : #{second_arr.slice(1, 2)}\n"
puts "slice() method result : #{third_arr.slice(1)}\n"

Output

It will produce the following output −

slice() method result : ["nil", "dog"]
slice() method result : [nil]
slice() method result :
raja
Updated on 12-Apr-2022 07:14:56

Advertisements