Q:

Ruby program to fetch elements from an array based on an index

belongs to collection: Ruby Arrays Programs

0

In this program, we will create an array of cities. Then we will get the city name based on the index using the fetch() method.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to fetch elements from an array based on an index is given below. The given program is compiled and executed successfully.

# Ruby program to fetch element from 
# array based on index

city = ["AGRA", "DELHI", "MUMBAI", "GWALIOR"];

print "Enter index: ";
index = gets.chomp.to_i;  

item = city.fetch(index);

print "City is: ",item,"\n";

Output:

Enter index: 2
City is: MUMBAI

Explanation:

In the above program, we created an array of city names. Here, we read the index from the user and fetched the element from the array based on the index. After that, we printed the fetched item.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby Arrays Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Ruby program to fill an array with a specific elem... >>
<< Ruby program to check an array is empty or not...