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. Unicode 💎
  5. Quote String
  6. Quote Long String
  7. Format String
  8. String Operations
  9. True, False
  10. “if then else”
  11. for, while, Loop
  12. List
  13. Loop Thru List
  14. Hash Table
  15. Function Optional Parameter
  16. Map f to List
  17. Complex Numbers
  18. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  19. Predefined Global Variables
  20. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?