Array shift function in Ruby

RubyServer Side ProgrammingProgramming

Sometimes we need to extract a portion of an array data and perform some operation on the extracted data. In Ruby, we can perform such operations with the help of the shift() function.

The shift() function takes one argument, which is an index that is used to remove the first element from that index and return all the elements before it. If the index is somehow invalid, then it returns nil.

Syntax

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

res = Array.shift(x)

Here, the argument "x" denotes the starting index.

Example 1

Now that we know a little about the shift() function on arrays, let's see how to use it in a Ruby 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]

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

Output

It will produce the following output −

shift() method result : [18]
shift() method result : [1, 4]
shift() method result : 18

Example 2

Let's consider one more example of how to use the shift() function.

# declaring the arrays
first_arr = ["abc", "nil", "dog"]
second_arr = ["cat", nil]
third_arr = ["cow", nil, "dog", "snake"]

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

Output

It will produce the following output −

shift() method result : ["abc"]
shift() method result : ["cat", nil]
shift() method result : cow
raja
Updated on 12-Apr-2022 07:12:40

Advertisements