How to access array Elements in Ruby
Last Updated :
24 Oct, 2019
In this article, we will learn how to access array elements in Ruby.
In Ruby, there are several ways to retrieve the elements from the array. Ruby arrays provide a lot of different methods to access the array element. But the most used way is to use the index of an array.
Using Index –
str = [ "GFG" , "G4G" , "Sudo" , "Geeks" ]
puts str[ 1 ]
puts str[- 1 ]
|
Output:
G4G
Geeks
Retrieving Multiple Elements from Array:
Sometimes, we need to access the multiple elements from the array. So to access the multiple elements, pass the two specified array index into the [].
str = [ "GFG" , "G4G" , "Sudo" , "Geeks" ]
puts str[ 2 , 3 ]
|
Output:
Sudo
Geeks
For multi-dimensional array
str = [[ "GFG" , "G4G" , "Sudo" ],
[ "Geeks" , "for" , "portal" ] ]
puts str[ 1 ][ 2 ]
|
Output:
portal
Share your thoughts in the comments
Please Login to comment...