Open In App

How to access array Elements in Ruby

Last Updated : 24 Oct, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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 –




# Ruby program to demonstrate the  
# accessing the elements of the array 
    
# creating string using [] 
str = ["GFG", "G4G", "Sudo", "Geeks"
    
# accessing array elements 
# using index 
puts str[1
    
# using the negative index 
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 [].




# Ruby program to demonstrate the  
# accessing the multiple elements  
# from  array 
    
# creating string using [] 
str = ["GFG", "G4G", "Sudo", "Geeks"
    
# accessing multiple array elements 
puts str[2, 3


Output:

Sudo
Geeks

For multi-dimensional array




# Ruby program to demonstrate the  
# accessing the multiple elements  
# from  array 
    
# creating string using [] 
str = [["GFG", "G4G", "Sudo"], 
       [ "Geeks", "for", "portal"] ]
    
# accessing item from multi-array
puts str[1][2


Output:

portal


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads