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

Ruby Comments

Comments are non executable code which describes the programming code.

Like PerlBash, and C Shell, Ruby uses the hash symbol (also called Pound Sign, number sign, Square, or octothorpe) for comments. Everything from the hash to the end of the line is ignored when the program is run by Ruby. For example, here's our hello-world.rb program with comments.
# My first Ruby program
# On my way to Ruby fame & fortune!
 
puts 'Hello world'
click on execute to see its output
You can append a comment to the end of a line of code, as well. Everything before the hash is treated as normal Ruby code.
puts 'Hello world'                # Print out "Hello world"
Click on execute to see its output, change the code to try different output/text
You can also comment several lines at a time:
=begin
This program will
print "Hello world".
=end
 
puts 'Hello world'

Click on execute to see its output

Hello World Ruby Program

Every programming language starts with Hello World Program.
Here is Hello World Ruby Program.

Create a text file called hello-world.rb containing the following code:
puts 'Hello world'
Now run it at the shell prompt.
$ ruby hello-world.rb
Hello world
You can also run the short "hello world" program without creating a text file at all. This is called a one-liner.
$ ruby -e "puts 'Hello world'"
Hello world
You can run this code with irb, but the output will look slightly different. puts will print out "Hello world", but irb will also print out the return value of puts – which is nil.
$ irb
>> puts "Hello world"
Hello world
=> nil

 object oriented version of Hello World Program
class HelloWorld
   def initialize(name)
      @name = name.capitalize
   end
   def sayHi
      puts "Hello #{@name}!"
   end
end

hello = HelloWorld.new("World")
hello.sayHi
execute online