How to get largest of two numbers using ternary operator in Ruby
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 numbersno1 = 23no2 = 4no3 = 55no4 = 200# create function to get largest numbersdef getLargest (num1, num2)largest = 0largest = num1 > num2 ? num1 : num2puts "The largest between #{num1} and #{num2} is #{largest}"end# check largest between numbersgetLargest(no1, no2)getLargest(no2, no3)getLargest(no3, no4)getLargest(no4, no1)
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 calledlargest. 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.