Tuesday, June 25, 2013

Conditional statements in Ruby Programming Language

Conditional statements excute on satisfaction of condition/expression.
Following are conditional statements

  1. If statement
  2. Unless statement
  3. If else statement
  4. Else if statement
1.If Statement
  • syntax:
    • if <conditon>
      • statements
    • end
  • example:
  • execute the statements if condition evaluate to true
  • conditon value is false or nil => it won't execute
  • zero is also true in ruby language
  •  a = 5
     if a == 4
       a = 7
     end
     print a # prints 5 since the if-block isn't executed
execute online

  •      short form for above code

2
3
4
a=1
flag = 1
flag = 0 if a == 0
puts flag



2.If else Statement

  • Syntax
          if <condition>
            <ifstatements>
        else
           <elsestatements>
        end
  • Example

1
2
3
4
5
6
a = 0
if a==0
 puts 'a is zero'
else 
 puts 'a is nonzero'
end
  • description
    • Execute <ifstatements>block if condition evaluate to tru
    • otherwise executes <elsestatements>block
  • execute online

No comments:

Post a Comment