Ruby Program for Linear Search with Example and Explanation
each_with_index and returns the index if the element matches, like array.each_with_index { |item, index| return index if item == target }.Examples
How to Think About It
Algorithm
Code
def linear_search(array, target)
array.each_with_index do |item, index|
return index if item == target
end
-1
end
# Example usage
arr = [3, 5, 7, 9]
target = 7
puts linear_search(arr, target)Dry Run
Let's trace the search for target 7 in the array [3, 5, 7, 9].
Check first element
item = 3, target = 7, not equal, continue
Check second element
item = 5, target = 7, not equal, continue
Check third element
item = 7, target = 7, equal, return index 2
| Index | Item | Compare with Target | Match? |
|---|---|---|---|
| 0 | 3 | 3 == 7 | No |
| 1 | 5 | 5 == 7 | No |
| 2 | 7 | 7 == 7 | Yes |
Why This Works
Step 1: Loop through each element
The code uses each_with_index to check every element and keep track of its position.
Step 2: Compare element with target
Inside the loop, it compares the current element with the target using ==.
Step 3: Return index if found
If the element matches the target, the function immediately returns the current index.
Step 4: Return -1 if not found
If the loop finishes without finding the target, the function returns -1 to show the target is not in the array.
Alternative Approaches
def linear_search(array, target) for i in 0...array.length return i if array[i] == target end -1 end puts linear_search([3, 5, 7, 9], 7)
def linear_search(array, target) array.index(target) || -1 end puts linear_search([3, 5, 7, 9], 7)
Complexity: O(n) time, O(1) space
Time Complexity
The search checks each element once until it finds the target or reaches the end, so it takes linear time proportional to the array size.
Space Complexity
The search uses only a few variables and no extra arrays, so it uses constant extra space.
Which Approach is Fastest?
All approaches have the same time complexity O(n), but using Ruby's built-in index method is simplest and often fastest due to internal optimizations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| each_with_index loop | O(n) | O(1) | Clear code with index access |
| for loop | O(n) | O(1) | Beginners familiar with classic loops |
| Array#index method | O(n) | O(1) | Shortest code and built-in optimization |
each_with_index to get both element and position easily during linear search.