Ruby: “if then else” Example

By Xah Lee. Date:

Example of “if”:

#-*- coding: utf-8 -*-
# ruby

# example of if
x = 1
p (if x == 1 then 'yes' end) # yes

Example of “if else”:

#-*- coding: utf-8 -*-
# ruby

# example of if else
y = 2
p (if y == 1 then 'yes' else 'no' end) # no

Example of “if else” chain:

#-*- coding: utf-8 -*-
# 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
  )

Note: Ruby if statement is also a expression. It returns the last value of the executed block.

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode 💎
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. “if then else”
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables