How to use Index – In Ruby




# 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

How to access array Elements in Ruby

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.

Similar Reads

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]...

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 []....

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]...

Contact Us