Related Tags

communitycreator
ruby
operator

# How to get largest of two numbers using ternary operator in Ruby

okwudili onyejiaku

### Overview

We use the ternary operator to find the largest of two numbers in Ruby. This operator is very popular in many programming languages. It takes three operands. One is the condition, another is the expressions to execute if the condition is true or false. For checking the largest of two, we create a condition that checks which one is the greatest. Then, if the first number is the greatest, we take the first number. Otherwise, we take the second number.

### Syntax

largestNumber = condition ? firstNumber : SecondNumber
Syntax for the ternary operator in Ruby

### Parameters

condition: This is the condition for the ternary operator. It returns a true or a false.

firstNumber: This is the number we get as the largest if the condition returns true.

secondNumber: This is the number that is not the largest if the condition returns a false.

### Example

# create some numbers
no1 = 23
no2 = 4
no3 = 55
no4 = 200

# create function to get largest numbers
def getLargest (num1, num2)
largest = 0
largest = num1 > num2 ? num1 : num2

puts "The largest between #{num1} and #{num2} is #{largest}"
end

# check largest between numbers
getLargest(no1, no2)
getLargest(no2, no3)
getLargest(no3, no4)
getLargest(no4, no1)
Get the largest of two numbers using ternary operator in Ruby

### Explanation

In the code above:

• Lines 2–5: We create some number variables.
• Line 8: We create a function getLargest() to get the greater of the two numbers. It takes two numbers as parameters. Using the ternary operator, it checks the largest between two numbers and assigns that value to a variable called largest. Then it prints the result to the console, which tells the user which of the numbers is the largest.
• Lines 16–19: We invoke the function we created and check for the largest between two numbers.

RELATED TAGS

communitycreator
ruby
operator

CONTRIBUTOR

okwudili onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 