Home »
Ruby Tutorial »
Ruby Programs
Ruby program to search an item into the array using linear search
Last Updated : December 15, 2025
Problem Solution
In this program, we will create an array of integer elements. Then we will read an item from the user to search into the array using linear search and print the index of the item in the array.
Program/Source Code
The source code to search an item into the array using linear search is given below. The given program is compiled and executed successfully.
# Ruby program to search an item into the array
# using linear search
arr = [12,45,23,39,37];
i = 0;
item = 0;
flag = 0;
print "Enter item: ";
item = gets.chomp.to_i;
flag = -1
while(i<arr.size)
if(arr[i]==item)
flag = i;
break;
end
i = i + 1;
end
if(flag>=0)
print "Item found at index: ",flag,"\n";
else
print "Item not found\n";
end
Output
Enter item: 39
Item found at index: 3
Explanation
In the above program, we created an array of integer elements. Then we read an item from the user to search into the array using a linear search mechanism. Here, we matched the input item in the array one by one. If an item is found in an array, then the index will be printed, otherwise, the "Item not found" message will be printed.
Ruby Arrays Programs »
Advertisement
Advertisement