Ruby Program to Find Largest of Three Numbers
max = [a, b, c].max or by comparing them with if statements like if a > b && a > c then max = a.Examples
How to Think About It
greater than checks. The number that is greater than both others is the largest.Algorithm
Code
puts "Enter three numbers:" a = gets.to_i b = gets.to_i c = gets.to_i if a > b && a > c max = a elsif b > c max = b else max = c end puts "The largest number is #{max}"
Dry Run
Let's trace the input a=3, b=7, c=5 through the code
Input numbers
a=3, b=7, c=5
Check if a > b and a > c
3 > 7 is false, so condition fails
Check if b > c
7 > 5 is true, so max = b = 7
Print result
The largest number is 7
| Step | Condition | Result | max |
|---|---|---|---|
| 1 | a > b && a > c | 3 > 7 && 3 > 5 = false | nil |
| 2 | b > c | 7 > 5 = true | 7 |
| 3 | Print max | - | 7 |
Why This Works
Step 1: Compare first number
We check if the first number is greater than both others using a > b && a > c to quickly find if it's the largest.
Step 2: Compare second and third
If the first is not largest, we compare the second and third numbers with b > c to find which is bigger.
Step 3: Assign and print largest
The largest number is assigned to max and printed using string interpolation for clear output.
Alternative Approaches
puts "Enter three numbers:" a = gets.to_i b = gets.to_i c = gets.to_i max = [a, b, c].max puts "The largest number is #{max}"
puts "Enter three numbers:" a = gets.to_i b = gets.to_i c = gets.to_i if a >= b if a >= c max = a else max = c end else if b >= c max = b else max = c end end puts "The largest number is #{max}"
Complexity: O(1) time, O(1) space
Time Complexity
The program does a fixed number of comparisons (at most 3), so it runs in constant time, O(1).
Space Complexity
Only a few variables are used to store inputs and the result, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in constant time, but using the array max method is more concise and idiomatic in Ruby.
| Approach | Time | Space | Best For |
|---|---|---|---|
| If-else comparisons | O(1) | O(1) | Clear logic for beginners |
| Array max method | O(1) | O(1) | Concise and idiomatic Ruby code |
| Nested if-else | O(1) | O(1) | Step-by-step comparison clarity |
max method on an array for a simple and clean solution.gets.to_i to convert input to numbers, causing string comparison errors.