What is array.dig() in Ruby?

Overview

The dig() method, as its name implies, extracts specific elements from arrays in Ruby. It can be used on multi-dimensional arrays.

Syntax

array.dig(idx, ...)

Parameters

idx: This is an integer value. It represents the index position of the element to be extracted. There can be one or more indexes passed to the array, depending on its dimensions. This index is mandatory.

Return value

This method returns an element from a specific location in the array. It returns nil if the element is not found.

Code example 1

The code below demonstrates the use of the dig() method on a two-dimensional array.

# Create an array
arr1 = [[1, [2, 3]]]
arr2 = [[1, 4], [ 1, 1, 88, 9]]
# Perform dig operations
a = arr1.dig(0, 1, 1)
b = arr1.dig(1, 2, 3)
c = arr2.dig(0, 1)
d = arr2.dig(1, 2)
# Print out returned values
puts a
puts b
puts c
puts d

Explanation

In the code above, we are able to select or dig out elements in a two-dimensional array using the dig() method.

In line 10, we pass index 0 and 0 to this method. This digs out the first element of the array.

Code example 2

The code below demonstrates the use of the dig() method on a multi-dimensional arrays.

# Create an array
arr1 = [[1, [2, 3]]]
arr2 = [[1, 4], [ 1, 1, 88, 9]]
# Perform dig operations
a = arr1.dig(0, 1, 1)
b = arr1.dig(1, 2, 3)
c = arr2.dig(0, 1)
d = arr2.dig(1, 2)
# print out returned values
puts a
puts b
puts c
puts d

Explanation

In the code above, we are able to select or dig out elements in a multi-dimensional array using the dig() method.

In the code above, execution was successful except for variable b. This is because the element cannot be found, so nothing is printed out for b in line 13.