Ruby Ternary operator
Ternary operator
Ternary operator logic uses "(condition) ? (true return value) : (false return value)" statements to shorten your if/else structures. It first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. Here is the syntax :
test-expression ? if-true-expression : if-false-expression
Advantages of Ternary Logic :
- Makes coding simple if/else logic quicker
- Makes code shorter
- Makes maintaining code quicker, easier
Example: Ruby ternary operator
# Example-1
var = 5;
var_is_greater_than_three = (var > 3 ? true : false);
puts var_is_greater_than_three
# Example-2
score= 50
result = score > 40 ? 'Pass' : 'Fail'
puts result
# Example-3
score = 10;
age = 22;
puts "Taking into account your age and score, you are : ",(age > 10 ? (score < 80 ? 'behind' : 'above average') : (score < 50 ? 'behind' : 'above average'));
# Example-4
score = 81
puts "Based on your score, you are a ", (score > 80 ? "genius" : "Not genius")
Output:
true Pass Taking into account your age and score, you are : behind Based on your score, you are a genius
Previous:
Ruby Logical Operators
Next:
Ruby Defined Operators
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/ruby/ruby-ternary-operator.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics