Skip to content

Instantly share code, notes, and snippets.

@boddhisattva
Created February 19, 2014 05:43
Show Gist options
  • Save boddhisattva/9086658 to your computer and use it in GitHub Desktop.
Save boddhisattva/9086658 to your computer and use it in GitHub Desktop.
Conditionals in Ruby
# Conditionals
a = 5
b = 3
# if else in operation..
if a < b
puts("true")
else
puts("false")
end
# if elsif else in operation..
if a < b
puts("a is less than b")
elsif a == b
puts("a is equal to b")
else
puts("a is greater than b")
end
# return value
x = 2
month = if x == 1 then "january"
elsif x == 2 then "february"
elsif x == 3 then "march"
elsif x == 4 then "april"
else "The Month is not either of the above four months"
end
puts(month)
# a different Avatar of if.. Ruby making things simpler..
puts x if x # if x is defined it will print the value of x.. do note..
#--------------------------------------------------------------------------------------------------------------------------------
# unless
unless a == 3 # this condition is false or nil.. the actual value of a is 5.. this condition works as the opposite of the if condition..
puts(" value of a is not 3 ")
end
# unless with else
unless x == 0
puts "x is not 0"
else
unless y == 0
puts "y is not 0"
else
unless z == 0
puts "z is not 0"
else
puts " all are zero "
end
end
end
#--------------------------------------------------------------------------------------------------------------------------------
# case
name = case
when x == 1 then "one"
when 2 == x then "two"
when x == 3 then "three"
when x == 4 then "four"
when x == 5 then "five"
else "nothing among the first five"
end
puts(name)
#--------------------------------------------------------------------------------------------------------------------------------
false
a is greater than b
february
2
value of a is not 3
x is not 0
two
@boddhisattva
Copy link
Author

Please note, I need to make code formatting changes above to follow Ruby's 2 space indent coding convention.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment