Ruby - Ternary operator

1. Introduction

The ternary operator in Ruby provides a shorthand way to express conditional statements. It's a concise alternative to the traditional if-else statement. The name "ternary" indicates that this operator takes three operands: a condition, a value if the condition is true, and a value if the condition is false.

2. Program Steps

1. Define a condition.

2. Use the ternary operator to evaluate the condition.

3. Print the result.

3. Code Program

# Define a sample variable
number = 15
# Check if the number is even or odd using the ternary operator
result = number.even? ? "even" : "odd"
puts "The number #{number} is #{result}."
# Another example: Check if a number is positive, negative, or zero
value = -5
description = value > 0 ? "positive" : (value < 0 ? "negative" : "zero")
puts "The number #{value} is #{description}."

Output:

The number 15 is odd.
The number -5 is negative.

Explanation:

1. The ternary operator has the syntax: condition ? value_if_true : value_if_false.

2. In the first example, the method even? checks if the number is even. If true, the result is "even", and if false, the result is "odd".

3. In the second example, we've demonstrated nested ternary operations. First, we check if the value is greater than 0. If it's true, the result is "positive". If false, we then check if the value is less than 0. If this inner condition is true, the result is "negative", otherwise, it's "zero".


Comments