ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.