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.
largestNumber = condition ? firstNumber : SecondNumber
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.
# 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)
In the code above:
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.