Ruby Language Reference

if statement

Syntax

if conditional
  code
elsif conditional
  code
else
  code
end

If statement executes code if the conditional is true. If the conditional is not true, code in the else clause is executed.

Example

traffic = :stop

if traffic == :stop
  p 'The traffic is at stop'
else
  p 'The traffic is flowing'
end

This prints:

The traffic is at stop

If statements are expressions that evaluate to a value, the result can be assigned to a variable:

traffic = :stop

status = if traffic == :stop
  'stopped'
else
  'flowing'
end


p status

This prints:

stopped

If in Statement Modifier

raining = true

p 'Take umbrella' if raining

This prints:

Take umbrella

If with Ternary Operators

raining = true

status = raining ? 'Take umbrella' : 'No umbrella'

p status

This prints:

Take umbrella

If with Elsif Keyword

skill = :advanced

level = if skill == :advanced
  'Guru'
elsif skill == :intermediate
  'Journey Man'
else
  'Newbie'
end

p level

This prints: 'Guru'.


Sharing is Caring