Tuesday, February 18, 2014

Conditionals in Ruby

Using Conditionals in Ruby - Part 1 - Source for the tutorial is Ruby Programming Language by Yukihiro Matsumoto(creator of Ruby) and David Flanagan.

The blog below has a sample code with output. The sample code below with inline comments in a way summarizes the concept(refer blog title) covered as part of the book.

# 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)
#--------------------------------------------------------------------------------------------------------------------------------
view raw conditionals.rb hosted with ❤ by GitHub
false
a is greater than b
february
2
value of a is not 3
x is not 0
two


No comments:

Post a Comment