Nested Arrays are the one in which, a block of Array can contain another Array.
Say for example, let us take the below Array.
So, if you see the second location or index/position 1 of the above Array. There is another Array of two elements containing the names Satyam and Rishab stored in it.
This Array is an example of Nested Array.
Let us create the above Nested Array.
x = ["Mohan", [ "Satyam", "Rishab"] , "Paul", "Kriti", "Salim"] puts "The first element of the nested Array is : #{x[1][0]}" puts "The second element of the nested Array is : #{x[1][1]}"
So, in the above example, we have declared a Nested Array and initialised it to x.
x = ["Mohan", [ "Satyam", "Rishab"] , "Paul", "Kriti", "Salim"]
Now, let us see the diagram,
And as we can see, the names Satyam and Rishab is located at the second location of x.
So, to access Satyam, we need to goto index 1 of the Array and then goto the index of Satyam i.e. Index 0.
i.e. x[1][0]
And thus the print statement prints Satyam.
puts "The first element of the nested Array is : #{x[1][0]}"
Similarly, to access Rishab, we need to goto index 1 of the Array and then goto the index of Rishab i.e. Index 1.
i.e. x[1][1]
And thus the print statement prints Satyam.
puts "The second element of the nested Array is : #{x[1][1]}"
Now, what if we want to find out the first letter of Rishab or the second letter of Paul.
x = ["Mohan", [ "Satyam", "Rishab"] , "Paul", "Kriti", "Salim"] puts "The first letter of Rishab is : #{x[1][1][0]}" puts "The second letter of Paul is : #{x[2][1]}"
So, in the above example, we have declared a Nested Array and initialised it to x.
x = ["Mohan", [ "Satyam", "Rishab"] , "Paul", "Kriti", "Salim"]
So, we have the same diagram,
Similarly, to access the first letter of i.e. R of Rishab,
- We need to goto Rishab
- And as we have seen, to access Rishab, we need to goto index 1 of the Array and then goto the index of Rishab i.e. Index 1.
- Which would be x[1][1]. And x[1][1] is the location where Rishab lies.
- Now, if we further subdivide Rishav. It would be,
- And the R of Rishav lies in the 0th location.
- So, the finally to reach R of Rishav, the location is x[1][1][0].
- Where x[1][1] is the location of Rishav and 0 is the location of R. Which is x[1][1][0].
And thus the print statement, prints the first letter of Rishav.
puts "The first letter of Rishab is : #{x[1][1][0]}"
And the same way, the print statement prints the second letter of Paul, i.e. a.
puts "The second letter of Paul is : #{x[2][1]}"