Ruby - Operator Ternary Operator

Introduction

The ternary operator is like a mini if/else statement.

Demo

age = 10 
type = age < 18 ? "child" : "adult" 
puts "You are a " + type

Result

The second line contains the ternary operator.

The structure is as follows:

<condition> ? <result if condition is true> : <result if condition is false> 

Consider an alternative:

Demo

age = 10 
type = 'child' if age < 18 
type = 'adult' unless age < 18 
puts "You are a " + type

Result

Another alternative is to use the multiline if/else option:

Demo

age = 10 
if age < 18 #  ww  w.ja  v a2s . c  om
 type = 'child' 
else 
 type = 'adult' 
end 
puts "You are a " + type

Result

Consider this even simpler version of the first example from this section:

Demo

age = 10 
puts "You are a " + (age < 18 ? "child" : "adult")

Result