Ruby: If Then Else

By Xah Lee. Date: . Last updated: .

Ruby “if” is a expression. It returns the last value of the executed block.

Tip: “everything” in Ruby is a expression. They return a value.

# ruby

xx = 4

p(if xx > 0 then true end)

# formatted in multiple lines
p(if xx > 0 then
  true
end)

Example of “if else”:

# ruby

# example of if else
y = 2
p((if y == 1 then 3 else 4 end) == 4)

Example of “if else” chain:

# ruby

# example of if else chain

z = 2
p((
  if z < 0 then
    'neg'
  elsif z == 0 then
    'zero'
  elsif z == 1 then
    'one'
  else
    'other'
  end
  ) == "other")

Short Form of If Expression

# ruby

# short form
p( 3 > 2 ? true : false)

Ruby Tutorial

Print

String

Types

Variable

Boolean

Branching

Loop, Iteration

Data Structure

Function

Misc