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

Ruby Example: Write a program to fetch elements from an array based on an index.
Submitted by Nidhi, on January 17, 2022

Problem Solution:

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.

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.

Ruby Arrays Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.