0
0
RubyProgramBeginner · 2 min read

Ruby Program to Find Largest Element in Array

In Ruby, you can find the largest element in an array using array.max. For example, largest = [3, 7, 2, 9].max will set largest to 9.
📋

Examples

Input[1, 2, 3, 4, 5]
Output5
Input[10, 5, 20, 15]
Output20
Input[-3, -1, -7, -4]
Output-1
🧠

How to Think About It

To find the largest number in an array, look at each number one by one and remember the biggest number you have seen so far. Keep updating this biggest number if you find a bigger one until you finish checking all numbers.
📐

Algorithm

1
Start with the first element as the largest number.
2
Go through each element in the array one by one.
3
If the current element is bigger than the largest number, update the largest number.
4
After checking all elements, return the largest number.
💻

Code

ruby
array = [3, 7, 2, 9]
largest = array.max
puts "The largest number is #{largest}"
Output
The largest number is 9
🔍

Dry Run

Let's trace the array [3, 7, 2, 9] through the code to find the largest number.

1

Initialize array

array = [3, 7, 2, 9]

2

Find max

largest = array.max # largest = 9

3

Print result

Output: The largest number is 9

IterationCurrent ElementLargest So Far
133
277
327
499
💡

Why This Works

Step 1: Use built-in max method

Ruby's max method automatically checks all elements and returns the largest one.

Step 2: Store the largest value

We save the result of array.max in a variable to use it later.

Step 3: Display the result

Using puts, we print the largest number in a friendly message.

🔄

Alternative Approaches

Manual iteration
ruby
array = [3, 7, 2, 9]
largest = array[0]
array.each do |num|
  largest = num if num > largest
end
puts "The largest number is #{largest}"
This method shows how to find the largest number without using built-in methods, useful for learning.
Using sort
ruby
array = [3, 7, 2, 9]
largest = array.sort[-1]
puts "The largest number is #{largest}"
Sorting the array and picking the last element works but is less efficient than using <code>max</code>.

Complexity: O(n) time, O(1) space

Time Complexity

The max method checks each element once, so it takes time proportional to the number of elements, which is O(n).

Space Complexity

No extra space is needed besides a variable to store the largest number, so space complexity is O(1).

Which Approach is Fastest?

Using max is fastest and simplest. Sorting is slower (O(n log n)) and manual iteration is similar in speed but more code.

ApproachTimeSpaceBest For
Using maxO(n)O(1)Simple and fast for all arrays
Manual iterationO(n)O(1)Learning how to find max without built-ins
SortingO(n log n)O(n)When you also need sorted data
💡
Use Ruby's built-in max method for a simple and fast way to find the largest element.
⚠️
Beginners sometimes forget to handle empty arrays, which causes errors when calling max.