SlideShare a Scribd company logo
1 of 27
Deepak H B
Full-Stack Developer
Gmail: deepakhb2@gmail.com
Linkedin: http://in.linkedin.com/in/deepakhb
GitHub: https://github.com/deepakhb2
Statements and Control
Structures
Introduction
• Ruby’s control structure, which alter the sequential
execution or flow-of-control of a program.
• Conditionals
• Loops
• Iterators and blocks
• Flow altering statements like return and break
Conditionals
• The most common control structure, in any
programming language, is the conditional.
• The condition is the expression, if it evaluates to any
value other than false or nil, then the condition is
satisfied.
If
• The simplest form, it looks like
if expression
code
end
• The code between if and end is executed if the expression is evaluated
other than false or nil.
• The code must be separated from the expression with a newline or
semicolon or the keyword then.
• Parentheses are not required around the conditional expression.
• The end keyword is required even if the code to be executed consists for
single statement.
• The return value of an if “statement” is the value of the last expression in
the code that was executed or nil if no block of code was executed.
Else
• If statement may include an else clause to specify code to be
executed if the condition is not true.
if expression
code
else
code
end
• The else and end keywords fully delimit the second chunk of
code.
Elsif
• If you want to test more than one condition within a conditional, you can add one
or more elsif clause between an if and an else.
if expression1
code1
elsif expresion2
code2
.
.
elsif expression
codeN
else
code
end
• If expression1 evaluates to anything other than false or nil, then code1 is executed.
Otherwise, expression2 is evaluated. This continuous till last elsif.
• Finally, if else clause is not present, than no code is executed at all.
• elsif is like if: the expression must be separated from the code by a newline, a
semicolon, or a then keyword.
if as a Modifier
• The if expression can also be written as:
$code if expression
• When used in this form, if is known as a statement
modifier.
• Even though the condition is written last, it is evaluated
first.
• Code is evaluated depending on the condition evaluation
and expression value is returned (value or nil).
Unless
• A statement or a modifier, is the opposite of if: It executes code only if an
associated expression evaluates to false or nil.
• Its syntax is just like if, except that elsif clause is not allowed.
unless condition
code
end
#two ways unless statement
unless condition
Code
else
Code
end
#unless modifier
code unless condition
• Like if, unless statements are expressions and return the value of the code
they execute or nil if they execute nothing.
Case
• The case statement is a multiway conditional.
• These two side by side expressions are equivalent
name = case
when x==1 then “one”
when x ==2 then “two”
when x==3 then “three”
when x ==4 then “four”
else “many”
end
name = if x==1 then “one”
elsif x ==2 then “two”
elsif x==3 then “three”
elsif x==4 then “four”
else “many”
end
Contd..
• The case statement returns value of the expression just like
if statement does.
• The then keyword following when can be replaced with
‘newline’ or “colon”
• The case statement tests each of its when expressions in
the order they are written until it finds one that evaluates
to true.
• The case statement may have more than one comma-
separated expression associated with it.
when x==1, y==2
Contd..
• The other way of writing case statement:
name = case x
when 1
“one”
when 2 then “two”
when 3; “three”
else “many”
end
• In this form of case statement, the expression associated with the
case is evaluated first and then its compared to the value obtained
by evaluating the when expression.
• This comparison is done using the === (case equality operator). This
operation is invoked on the value of the when expression and is
passed the value of the case expression.
• When multiple expressions are separated by comma, and the “===”
operator is invoked on each one.
The ?: Operator
• The conditional operator ?: behaves much like
an if statement, with ? replacing then and :
replacing else.
(n==1) ? “message1” : “message2”
Loops
While and until
• While and until will execute a chunk of code while a certain
condition is true or until the condition becomes true.
x=10
while x >= 0 do
puts x
x=x-1
end
x=0
until x>10 do
puts x
x=x+1
end
Contd..
• Loop condition is the Boolean expression that appears
between the while and until and do keywords.
• The loop body is the ruby code that appears between the
do and the end keyword.
• The while loop evaluates its condition. If the value is
anything other than false or nil it executes its body and
loops to evaluate its condition again.
• The until loop is the reverse. The condition is tested and the
body is executed if the condition evaluates to false or nil.
• The do keyword in a while or until loop is like the then
keyword in an if statement.
While and until as modifier
• These modifier syntax uses while keyword itself to separate the
loop body from the loop condition and avoids the need of do and
end keywords.
X=0
Puts x=x+1 while x<10
• Contrast this code with the more traditional while loop written on a
single line.
x=0
while x<10 do puts x=x+1 end
• Until can be used as a modifier just like while.
• When while and until are used as modifier, they must appear on the
same line as the loop body that they modify.
• The compound expression delimited by begin and end keywords,
then the body is executed first before the condition is tested.
x=10
begin
puts x
x=x-1
end until x==0
The for/in loop
• The for loop or for/in loop, iterates through the elements of
an enumerable object such as array.
for var in collection do
Body
End
• var is a variable or comma-separated list of variables,
collection is any object that has an each iterator method.
Arrays and Hashes define the each iterator method.
• The for/in loop will call the each method of the specified
object.
• The loop variable or variables of a for loop are not local to
the loop; then remain defined even after the loop exits.
Contd..
• As the iterator yields the values , the for loop assigns each value to
the specified variable and then executes the code in body.
array = [1,2,3,4]
for element in array
puts element
end
hash = {:a=>1, :b=>2, :c=>3}
for key,value in hash
puts “#{key} => #{value}”
End
• Similarly new variables defined in loop body continue to exists after
the loop exits.
• The values of the hash & array can be iterated using each iteratore
array.each do |v|
puts v
end
Iterators and Enumerable objects
• Its common in ruby to write loops using special methods
known as iterators.iterators.
3.times {puts “Thank you”}
data.each {|x| puts x}
[1,2,3].map {|x| x*x}
• The times, each, map and upto methods are all iterators and
they interact with the block of code that follows them.
• The complex control structure behind this is yield.
• The yield statement temporarily returns control from the
interator method to method that invoked the iterator.
Numeric Iterators
• The Integer class defines three commonly used iterators upto,
downto and times.
• The upto method invokes its associated block once for each
integer between the integer on which it is invoked and the integer
which is passed as an argument.
4.upto(6) {|x| puts x} # => prints “456”
• The downto method is just like upto but iterates from a larger
number down to a smaller number.
• The times method is invoked on the integer n, and it invokes its
block n times, passing values 0 through n-1 on successive
iterations.
• The step method is used to iterate through floating point numbers.
0.step(1, 0.1){|x| puts x}
Enumerable Iterators
• Array, Hash, Range and a number of other classes define an
each iterator that passes each element of the collection to
associated block.
• This is perhaps most commonly used iterator in Ruby.
[1,2,3].each {|x| print x}
• Ruby’s IO class defines an each iterator that yields lines of
text read from the Input/Output object.
• Most classes define an each method also include the
Enumerable module. The other iterator is each_with_index.
• Some of the most commonly used Enumerable iterators are
collect, select, reject, and inject.
Contd..
• The collect method executes its associated block for each element of the
enumerable object and collects the return values of the block to an array.
[1,2,3].collect{|x| x*x} #=> [1,4,9]
• The select method invokes the block for each element in an enumerable
object and returns an array of elements for which the block returns a
value other than false or nil.
(0..10).select{|x| x%2 == 0} #=> [2,4,6,8,10]
• The reject method is simply opposite of select.
(0..10).reject{|x| x%2==0} #=> [1,3,5,7,9]
• The inject method invokes the associated block with two arguments. The
first argument is accumulated value of some sort form previous iterations.
The second argument is the next element of the enumerable object. The
return value of the block will be the first block argument for the next
iteration or becomes the return value of the iterator after the last
iteration.
data = [2,5,3,4]
sum = data.inject{|sum, x| sum+x} # => 14
Writing Custom Iterators
• The defining feature of the iterator method is that it invokes a
block of code associated with the method invocation.
• You do this with the yield statement.
def twice
yield
yield
End
• To pass argument values to the block, follow the yield
statement with a comma separated list of expressions.
• Using the yield keyword is really is a lot like invoking a
method.
Altering Control Flow
Ruby supports a number of statements that alter the flow-of-control in a
Ruby program.
Return
• The return statement causes the enclosing method to return to its caller.
• Return may optionally followed by an expression or a comma-separated
list of expressions.
• If there is no expression, then the return value of a method is nil.
• If there is more than one expression after the return keyword, then the
return value of a method is an array containing the values of those
expressions.
• The method will automatically returns the last statement of the method if
there is no return statement.
Contd..
Break
• When used with loop, the break statement transfers the control out of the
loop to the first expression following the loop.
while(line = gets.chop)
break if line == “quit”
puts eval(line)
end
• When used in block, break transfers the control out of block, out of
iterator that invoked the block.
f.each do |line|
break if line == “puitn”
puts eval(line)
End
• The break statement can return the value when break is followed with
expression or comma separated expressions.
Contd..
Next
• The next statement causes a loop or iterator to end the current
iteration and begin the next.
while(line = gets.chop)
next if line[0,1] == “#”
puts eval(line)
End
• The next may be used alone or it may be followed by an expression
or a comma separated list of expressions. In loops the expressions
following next are ignored.
• In block, the expression or expressions become the “return value”
of the yield statement that invoked the block.
Contd..
Redo
• The redo statement restarts the current iteration of a loop or iterator.
• The redo will return the control back to the top of the loop or block so
the iteration can start over.
• It does not reset the loop condition and it does not fetch the next
element from an iterator. Its not normally used statement.
i=0
while(i<3)
print i
i+=1
redo if i==3
end

More Related Content

What's hot

[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
yasir_cesc
 
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in java
Shashwat Shriparv
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constants
TAlha MAlik
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 

What's hot (20)

Class 4: Making Procedures
Class 4: Making ProceduresClass 4: Making Procedures
Class 4: Making Procedures
 
Arrays
ArraysArrays
Arrays
 
Effective Java - Methods Common to All Objects
Effective Java - Methods Common to All ObjectsEffective Java - Methods Common to All Objects
Effective Java - Methods Common to All Objects
 
Cheat Sheet java
Cheat Sheet javaCheat Sheet java
Cheat Sheet java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Control structures selection
Control structures   selectionControl structures   selection
Control structures selection
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
M C6java2
M C6java2M C6java2
M C6java2
 
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in java
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
6 Object Oriented Programming
6 Object Oriented Programming6 Object Oriented Programming
6 Object Oriented Programming
 
Unit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cUnit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in c
 
M C6java3
M C6java3M C6java3
M C6java3
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constants
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
StringTokenizer in java
StringTokenizer in javaStringTokenizer in java
StringTokenizer in java
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
 
DITEC - Programming with Java
DITEC - Programming with JavaDITEC - Programming with Java
DITEC - Programming with Java
 

Similar to 5 Statements and Control Structures

Similar to 5 Statements and Control Structures (20)

Lecture_11.pdf
Lecture_11.pdfLecture_11.pdf
Lecture_11.pdf
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
 
c++ Data Types and Selection
c++ Data Types and Selectionc++ Data Types and Selection
c++ Data Types and Selection
 
Branch and Bound.pptx
Branch and Bound.pptxBranch and Bound.pptx
Branch and Bound.pptx
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Vbscript
VbscriptVbscript
Vbscript
 
Ruby basics ||
Ruby basics ||Ruby basics ||
Ruby basics ||
 
MODULE_2_Operators.pptx
MODULE_2_Operators.pptxMODULE_2_Operators.pptx
MODULE_2_Operators.pptx
 
CPP04 - Selection
CPP04 - SelectionCPP04 - Selection
CPP04 - Selection
 
Stoop 300-block optimizationinvw
Stoop 300-block optimizationinvwStoop 300-block optimizationinvw
Stoop 300-block optimizationinvw
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Looping statements
Looping statementsLooping statements
Looping statements
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 

More from Deepak Hagadur Bheemaraju (8)

12 Introduction to Rails
12 Introduction to Rails12 Introduction to Rails
12 Introduction to Rails
 
11 Ruby Gems
11 Ruby Gems11 Ruby Gems
11 Ruby Gems
 
10 Networking
10 Networking10 Networking
10 Networking
 
9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
 
8 Exception Handling
8 Exception Handling8 Exception Handling
8 Exception Handling
 
7 Methods and Functional Programming
7  Methods and Functional Programming7  Methods and Functional Programming
7 Methods and Functional Programming
 
3 Datatypes
3 Datatypes3 Datatypes
3 Datatypes
 
2 Basics
2 Basics2 Basics
2 Basics
 

Recently uploaded

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Recently uploaded (20)

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

5 Statements and Control Structures

  • 1. Deepak H B Full-Stack Developer Gmail: deepakhb2@gmail.com Linkedin: http://in.linkedin.com/in/deepakhb GitHub: https://github.com/deepakhb2
  • 3. Introduction • Ruby’s control structure, which alter the sequential execution or flow-of-control of a program. • Conditionals • Loops • Iterators and blocks • Flow altering statements like return and break
  • 4. Conditionals • The most common control structure, in any programming language, is the conditional. • The condition is the expression, if it evaluates to any value other than false or nil, then the condition is satisfied.
  • 5. If • The simplest form, it looks like if expression code end • The code between if and end is executed if the expression is evaluated other than false or nil. • The code must be separated from the expression with a newline or semicolon or the keyword then. • Parentheses are not required around the conditional expression. • The end keyword is required even if the code to be executed consists for single statement. • The return value of an if “statement” is the value of the last expression in the code that was executed or nil if no block of code was executed.
  • 6. Else • If statement may include an else clause to specify code to be executed if the condition is not true. if expression code else code end • The else and end keywords fully delimit the second chunk of code.
  • 7. Elsif • If you want to test more than one condition within a conditional, you can add one or more elsif clause between an if and an else. if expression1 code1 elsif expresion2 code2 . . elsif expression codeN else code end • If expression1 evaluates to anything other than false or nil, then code1 is executed. Otherwise, expression2 is evaluated. This continuous till last elsif. • Finally, if else clause is not present, than no code is executed at all. • elsif is like if: the expression must be separated from the code by a newline, a semicolon, or a then keyword.
  • 8. if as a Modifier • The if expression can also be written as: $code if expression • When used in this form, if is known as a statement modifier. • Even though the condition is written last, it is evaluated first. • Code is evaluated depending on the condition evaluation and expression value is returned (value or nil).
  • 9. Unless • A statement or a modifier, is the opposite of if: It executes code only if an associated expression evaluates to false or nil. • Its syntax is just like if, except that elsif clause is not allowed. unless condition code end #two ways unless statement unless condition Code else Code end #unless modifier code unless condition • Like if, unless statements are expressions and return the value of the code they execute or nil if they execute nothing.
  • 10. Case • The case statement is a multiway conditional. • These two side by side expressions are equivalent name = case when x==1 then “one” when x ==2 then “two” when x==3 then “three” when x ==4 then “four” else “many” end name = if x==1 then “one” elsif x ==2 then “two” elsif x==3 then “three” elsif x==4 then “four” else “many” end
  • 11. Contd.. • The case statement returns value of the expression just like if statement does. • The then keyword following when can be replaced with ‘newline’ or “colon” • The case statement tests each of its when expressions in the order they are written until it finds one that evaluates to true. • The case statement may have more than one comma- separated expression associated with it. when x==1, y==2
  • 12. Contd.. • The other way of writing case statement: name = case x when 1 “one” when 2 then “two” when 3; “three” else “many” end • In this form of case statement, the expression associated with the case is evaluated first and then its compared to the value obtained by evaluating the when expression. • This comparison is done using the === (case equality operator). This operation is invoked on the value of the when expression and is passed the value of the case expression. • When multiple expressions are separated by comma, and the “===” operator is invoked on each one.
  • 13. The ?: Operator • The conditional operator ?: behaves much like an if statement, with ? replacing then and : replacing else. (n==1) ? “message1” : “message2”
  • 14. Loops While and until • While and until will execute a chunk of code while a certain condition is true or until the condition becomes true. x=10 while x >= 0 do puts x x=x-1 end x=0 until x>10 do puts x x=x+1 end
  • 15. Contd.. • Loop condition is the Boolean expression that appears between the while and until and do keywords. • The loop body is the ruby code that appears between the do and the end keyword. • The while loop evaluates its condition. If the value is anything other than false or nil it executes its body and loops to evaluate its condition again. • The until loop is the reverse. The condition is tested and the body is executed if the condition evaluates to false or nil. • The do keyword in a while or until loop is like the then keyword in an if statement.
  • 16. While and until as modifier • These modifier syntax uses while keyword itself to separate the loop body from the loop condition and avoids the need of do and end keywords. X=0 Puts x=x+1 while x<10 • Contrast this code with the more traditional while loop written on a single line. x=0 while x<10 do puts x=x+1 end • Until can be used as a modifier just like while. • When while and until are used as modifier, they must appear on the same line as the loop body that they modify. • The compound expression delimited by begin and end keywords, then the body is executed first before the condition is tested. x=10 begin puts x x=x-1 end until x==0
  • 17. The for/in loop • The for loop or for/in loop, iterates through the elements of an enumerable object such as array. for var in collection do Body End • var is a variable or comma-separated list of variables, collection is any object that has an each iterator method. Arrays and Hashes define the each iterator method. • The for/in loop will call the each method of the specified object. • The loop variable or variables of a for loop are not local to the loop; then remain defined even after the loop exits.
  • 18. Contd.. • As the iterator yields the values , the for loop assigns each value to the specified variable and then executes the code in body. array = [1,2,3,4] for element in array puts element end hash = {:a=>1, :b=>2, :c=>3} for key,value in hash puts “#{key} => #{value}” End • Similarly new variables defined in loop body continue to exists after the loop exits. • The values of the hash & array can be iterated using each iteratore array.each do |v| puts v end
  • 19. Iterators and Enumerable objects • Its common in ruby to write loops using special methods known as iterators.iterators. 3.times {puts “Thank you”} data.each {|x| puts x} [1,2,3].map {|x| x*x} • The times, each, map and upto methods are all iterators and they interact with the block of code that follows them. • The complex control structure behind this is yield. • The yield statement temporarily returns control from the interator method to method that invoked the iterator.
  • 20. Numeric Iterators • The Integer class defines three commonly used iterators upto, downto and times. • The upto method invokes its associated block once for each integer between the integer on which it is invoked and the integer which is passed as an argument. 4.upto(6) {|x| puts x} # => prints “456” • The downto method is just like upto but iterates from a larger number down to a smaller number. • The times method is invoked on the integer n, and it invokes its block n times, passing values 0 through n-1 on successive iterations. • The step method is used to iterate through floating point numbers. 0.step(1, 0.1){|x| puts x}
  • 21. Enumerable Iterators • Array, Hash, Range and a number of other classes define an each iterator that passes each element of the collection to associated block. • This is perhaps most commonly used iterator in Ruby. [1,2,3].each {|x| print x} • Ruby’s IO class defines an each iterator that yields lines of text read from the Input/Output object. • Most classes define an each method also include the Enumerable module. The other iterator is each_with_index. • Some of the most commonly used Enumerable iterators are collect, select, reject, and inject.
  • 22. Contd.. • The collect method executes its associated block for each element of the enumerable object and collects the return values of the block to an array. [1,2,3].collect{|x| x*x} #=> [1,4,9] • The select method invokes the block for each element in an enumerable object and returns an array of elements for which the block returns a value other than false or nil. (0..10).select{|x| x%2 == 0} #=> [2,4,6,8,10] • The reject method is simply opposite of select. (0..10).reject{|x| x%2==0} #=> [1,3,5,7,9] • The inject method invokes the associated block with two arguments. The first argument is accumulated value of some sort form previous iterations. The second argument is the next element of the enumerable object. The return value of the block will be the first block argument for the next iteration or becomes the return value of the iterator after the last iteration. data = [2,5,3,4] sum = data.inject{|sum, x| sum+x} # => 14
  • 23. Writing Custom Iterators • The defining feature of the iterator method is that it invokes a block of code associated with the method invocation. • You do this with the yield statement. def twice yield yield End • To pass argument values to the block, follow the yield statement with a comma separated list of expressions. • Using the yield keyword is really is a lot like invoking a method.
  • 24. Altering Control Flow Ruby supports a number of statements that alter the flow-of-control in a Ruby program. Return • The return statement causes the enclosing method to return to its caller. • Return may optionally followed by an expression or a comma-separated list of expressions. • If there is no expression, then the return value of a method is nil. • If there is more than one expression after the return keyword, then the return value of a method is an array containing the values of those expressions. • The method will automatically returns the last statement of the method if there is no return statement.
  • 25. Contd.. Break • When used with loop, the break statement transfers the control out of the loop to the first expression following the loop. while(line = gets.chop) break if line == “quit” puts eval(line) end • When used in block, break transfers the control out of block, out of iterator that invoked the block. f.each do |line| break if line == “puitn” puts eval(line) End • The break statement can return the value when break is followed with expression or comma separated expressions.
  • 26. Contd.. Next • The next statement causes a loop or iterator to end the current iteration and begin the next. while(line = gets.chop) next if line[0,1] == “#” puts eval(line) End • The next may be used alone or it may be followed by an expression or a comma separated list of expressions. In loops the expressions following next are ignored. • In block, the expression or expressions become the “return value” of the yield statement that invoked the block.
  • 27. Contd.. Redo • The redo statement restarts the current iteration of a loop or iterator. • The redo will return the control back to the top of the loop or block so the iteration can start over. • It does not reset the loop condition and it does not fetch the next element from an iterator. Its not normally used statement. i=0 while(i<3) print i i+=1 redo if i==3 end