RORGURU.COM
 

Conditionals, Loops, Methods and Blocks

 

LOOPS :

Like other programming languages, Ruby also has its own unique looping statements. The usual loops we use in Ruby are for loop, do loop and while loop. Except these loops we also have some iteration mathods available.

  1. for loop
  2. while ..do loop
  3. each ..do loop

These three are the most common looping statements in Ruby.

(a) for loop : The syntax of this loop is as follows:

number = 1..5
for n in number
puts n
end

Output :

1
2
3
4
5

(b) while ..do loop : The sytax of while...do loop is given below: number = 5
while number >= 0 do
puts number
number = number – 1
end

Output :

1
2
3
4
5

Here is a similar way to define untill loop that acts just like while loop

number = 0
untill number > 5 do
puts number
number = number + 1
end

Output :

1
2
3
4
5

c) each ..do loop :The syntax of each ..do loop is given below:

number = 1..5
number.each do |n|
puts n
end

Output :

1
2
3
4
5
Except these loops, there are some special methods known as iterators. These iterators are very useful in Ruby. Some examples of how to use these iterators are given below:

3.times { puts "hello" }   # print hello three times
data.each {|d| puts d }   # print each element d in data
[1,2,3].map {|x| x*x }   # print square value of each
element in the array.
1.upto(5) { |n| puts n}   # print the values upto 5

CONDITIONS :

        The most common control logics for any programming language are the conditionals. So for Ruby, the following conditionals are very useful :

Example : a, b, c = 10, 20, 30.

        Parallel assignment is also useful for swapping the values in two variables:

Example:

a, b = b, c

2. Arithmetic Operators:

  Operator   Description
+ addition   Adds values
- subtraction   Subtracts values
* multiplication   Multiplies values
/ division   Divides left hand operand by
right hand operand
% modulus   Returns reminder
** exponent   Performs exponential (power) calculation on operators

3. Comparison Operators:

        Comparison operators are used to compare two values. Ruby has a number of such operators:

  1. if statement
  2. if .. else statement
  3. if .. elsif statement
  4. unless statement
  5. case statement
  6. ? : operator

(a) if statement : This statement starts with an if and closes with an end :

if (conditions)
statements..
end

Example :

number = 5
if number == 5
puts "The number is five. # if number equals to 5 the output will be "The number is five"
end

if number > 5
puts "The number is greater than five." # if number is greater than 5 the output will be "The number is greater
end # than five.

if number < 5
puts "The number is smaller than five." # if number is smaller than 5 the output will be "The number is
end # smaller than five."

(b) if .. else statement : This statement starts with if and closes with end and there is one more optional else which will come in use when the if condition fails.

if (conditions)
statements..
else
statements..
end

Example :

number = 5
if number == 5
puts "The number is equal to five."
else
puts "The number is not equal to five."
end

Here the output will be "The number is equal to five if the number equals to 5", otherwise the output will be "The number is not equal to five".

c) if .. elsif statement : This statement is optional. When we want to check multiple statement then we use the statement.

if (conditions)
statements..
elsif (conditions)
statements..
else
statements..
end

d) unless statement : The syntax of unless statement will be as follows :

unless (condtions)
statements..
else
statements..
end

Example :

number = 5
unless number > 5
puts " The number is smaller than five."
elsif number == 5
puts " The number is equal to five."
else
puts "The number is greater than five."
end

e) case statement :This is a multiway conditional statement. This is equivalent to alternative if/ elsif/ else statement:

case expression
when value
statements
when value
statements
.
.
.
else
statements
end

Example :

number = 5
case number
when 1
puts "The number is equal to one."
when 2
puts "The number is equal to two."
when 5
puts "The number is equal to five.
else
puts "This is not a number."
end

f) Ternary operator : This is a multiway conditional statement. This is equivalent to alternative if/ elsif/ else statement.

Except above conditional statements, R uby also provide this ? : operator. It behaves like a if statemnt, where ? replaces with then and : replaces with else.

var = expression ? true : false

Example :

number = 4
result = number == 4 ? "The number is equal to four. : " The number is not equal to four.

There is also nesting conditional statements. In this way multiple conditions can be checked.
Here is a simple example.

train = "go"
bus = "go"
auto = "go"
if train == "go"
if bus == "go"
if auto == "go"
puts " Person can reach the destination."
end
end
end

METHODS :

Ruby methods are very similar to the functions of our good old C/C++. This methods are used to handle the repeatative works.

By this method we make repeatative statements into a single unit. To declare method we have to always lower case and the declaration of a method must do before the calling the method.

The syntax to define a method is as follows :

1. Method without arguments :

def method_name
statements
.
.
end

2. Method with arguments :

def method_name (arguments)
statements
.
.
end

3. Method with returning value :

def method_name( a, b )
c = a + b
return c
end

Except the methods described above, we can also use class methods. These methods are especially useful in those situations when we want to acccess a method without making an instance of the class that contains those methods.

4. Class method :

class Wish
def self.helloM
puts "Hello world"
end
end

Here the method self.hello has been defined in Wish class is class method. To access the method we have to just write the code in following way.

Wish.hello
the output will be Hello world

BLOCK :

We have seen how code statements are defined in a method. In similar way we can use chunk of codes by defining a block. To define a block we have to follow some procedure. Those are stated below.

  1. Block have chunk of code
  2. Have to assign a name to block
  3. We use show code enclosed within the brace ({})
  4. To get block code we have to use yield

The syntax to declare a block, is given below

def block_name
statements..
yield
end
to get block we have to use block_name { }

Passing parameter with yield statement in block :

def block_name
statements.
Yield 6
puts "The block testing."
yield 50
end
block_name{|i| puts "You are in the block #{i}."}
the output will be
You are in the block 6
The block testing
You are in the block 50

To passing parameter to the block, we can access the block. We can pass parameters as arguments and blocks . For arguments we use * and for blocks we use & preceded by the parameters.
The following examples shows how to pass parameter as argument through the block.

def hello(n)
n.times {yield} if block_given?
end
hello(2) {puts "hello world"}
# hello world
# hello world
def hello(n, ∓block)
n.times {block.call} if block
end
hello(2) {puts "hello world"}
# hello world
# hello world
def hello(n, &block)
n.times{yield} if block
end
hello(2) {puts "hello world"}

Block argument will be always at the last position for passing parameter in a block. The example how to pass arguments and block parameter in a block is given bellow.

def call_each(*args, &block)
args.each {|arg| yield arg }
end
call_each(1, 2, 3, 4) { |x| puts x**2}
# 1
# 2
# 3
# 4