The dig()
method, as its name implies, extracts specific elements from arrays in Ruby. It can be used on multi-dimensional arrays.
array.dig(idx, ...)
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.
This method returns an element from a specific location in the array. It returns nil
if the element is not found.
The code below demonstrates the use of the dig()
method on a two-dimensional array.
# Create an arrayarr1 = [[1, [2, 3]]]arr2 = [[1, 4], [ 1, 1, 88, 9]]# Perform dig operationsa = arr1.dig(0, 1, 1)b = arr1.dig(1, 2, 3)c = arr2.dig(0, 1)d = arr2.dig(1, 2)# Print out returned valuesputs aputs bputs cputs d
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.
The code below demonstrates the use of the dig()
method on a multi-dimensional arrays.
# Create an arrayarr1 = [[1, [2, 3]]]arr2 = [[1, 4], [ 1, 1, 88, 9]]# Perform dig operationsa = arr1.dig(0, 1, 1)b = arr1.dig(1, 2, 3)c = arr2.dig(0, 1)d = arr2.dig(1, 2)# print out returned valuesputs aputs bputs cputs d
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.