SlideShare uma empresa Scribd logo
1 de 6
Baixar para ler offline
RUBY LOOPS - WHILE, FOR, UNTIL, BREAK, REDO AND RETRY
http://www.tutorialspoint.com/ruby/ruby_loops.htm                                              Copyright © tutorialspoint.com



Loops in Ruby are used to execute the same block of code a specified number of times. This chapter details all the loop
statements supported by Ruby.

Ruby while Statement:

Syntax:

 while conditional [do]
    code
 end


Executes code while conditional is true. A while loop's conditional is separated from code by the reserved word do, a
newline, backslash , or a semicolon ;.

Example:

 #!/usr/bin/ruby

 $i = 0
 $num = 5

 while $i < $num do
    puts("Inside the loop i = #$i" )
    $i +=1
 end


This will produce following result:

 Inside    the   loop   i   =   0
 Inside    the   loop   i   =   1
 Inside    the   loop   i   =   2
 Inside    the   loop   i   =   3
 Inside    the   loop   i   =   4


Ruby while modifier:

Syntax:

 code while condition

 OR

 begin
   code
 end while conditional


Executes code while conditional is true.

If a while modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional
is evaluated.

Example:

 #!/usr/bin/ruby
$i = 0
 $num = 5
 begin
    puts("Inside the loop i = #$i" )
    $i +=1
 end while $i < $num


This will produce following result:

 Inside   the   loop   i   =   0
 Inside   the   loop   i   =   1
 Inside   the   loop   i   =   2
 Inside   the   loop   i   =   3
 Inside   the   loop   i   =   4


Ruby until Statement:

 until conditional [do]
    code
 end


Executes code while conditional is false. An until statement's conditional is separated from code by the reserved word
do, a newline, or a semicolon.

Example:

 #!/usr/bin/ruby

 $i = 0
 $num = 5

 until $i > $num do
    puts("Inside the loop i = #$i" )
    $i +=1;
 end


This will produce following result:

 Inside   the   loop   i   =   0
 Inside   the   loop   i   =   1
 Inside   the   loop   i   =   2
 Inside   the   loop   i   =   3
 Inside   the   loop   i   =   4
 Inside   the   loop   i   =   5


Ruby until modifier:

Syntax:

 code until conditional

 OR

 begin
    code
 end until conditional


Executes code while conditional is false.

If an until modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional
is evaluated.
Example:

 #!/usr/bin/ruby

 $i = 0
 $num = 5
 begin
    puts("Inside the loop i = #$i" )
    $i +=1;
 end until $i > $num


This will produce following result:

 Inside   the   loop   i   =   0
 Inside   the   loop   i   =   1
 Inside   the   loop   i   =   2
 Inside   the   loop   i   =   3
 Inside   the   loop   i   =   4
 Inside   the   loop   i   =   5


Ruby for Statement:

Syntax:

 for variable [, variable ...] in expression [do]
    code
 end


Executes code once for each element in expression.

Example:

 #!/usr/bin/ruby

 for i in 0..5
    puts "Value of local variable is #{i}"
 end


Here we have defined the range 0..5. The statement for i in 0..5 will allow i to take values in the range from 0 to 5
(including 5).This will produce following result:

 Value    of   local   variable    is   0
 Value    of   local   variable    is   1
 Value    of   local   variable    is   2
 Value    of   local   variable    is   3
 Value    of   local   variable    is   4
 Value    of   local   variable    is   5


A for...in loop is almost exactly equivalent to:

 (expression).each do |variable[, variable...]| code end


except that a for loop doesn't create a new scope for local variables. A for loop's expression is separated from code by
the reserved word do, a newline, or a semicolon.

Example:

 #!/usr/bin/ruby

 (0..5).each do |i|
    puts "Value of local variable is #{i}"
end


This will produce following result:

 Value   of   local   variable   is   0
 Value   of   local   variable   is   1
 Value   of   local   variable   is   2
 Value   of   local   variable   is   3
 Value   of   local   variable   is   4
 Value   of   local   variable   is   5


Ruby break Statement:

Syntax:

 break


Terminates the most internal loop. Terminates a method with an associated block if called within the block (with the
method returning nil).

Example:

 #!/usr/bin/ruby

 for i in 0..5
    if i > 2 then
       break
    end
    puts "Value of local variable is #{i}"
 end


This will produce following result:

 Value of local variable is 0
 Value of local variable is 1
 Value of local variable is 2


Ruby next Statement:

Syntax:

 next


Jumps to next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or
call returning nil).

Example:

 #!/usr/bin/ruby

 for i in 0..5
    if i < 2 then
       next
    end
    puts "Value of local variable is #{i}"
 end


This will produce following result:

 Value of local variable is 2
Value of local variable is 3
 Value of local variable is 4
 Value of local variable is 5


Ruby redo Statement:

Syntax:

 redo


Restarts this iteration of the most internal loop, without checking loop condition. Restarts yield or call if called within a
block.

Example:

 #!/usr/bin/ruby

 for i in 0..5
    if i < 2 then
       puts "Value of local variable is #{i}"
       redo
    end
 end


This will produce following result and will go in an infinite loop:

 Value of local variable is 0
 Value of local variable is 0
 ............................


Ruby retry Statement:

Syntax:

 retry


If retry appears in rescue clause of begin expression, restart from the beginning of the 1begin body.

 begin
    do_something # exception raised
 rescue
    # handles error
    retry # restart from beginning
 end


If retry appears in the iterator, the block, or the body of the for expression, restarts the invocation of the iterator call.
Arguments to the iterator is re-evaluated.

 for i in 1..5
    retry if some_condition # restart from i == 1
 end


Example:

 #!/usr/bin/ruby

 for i in 1..5
    retry if i > 2
    puts "Value of local variable is #{i}"
 end
This will produce following result and will go in an infinite loop:

 Value of local variable is 1
 Value of local variable is 2
 Value of local variable is 1
 Value of local variable is 2
 Value of local variable is 1
 Value of local variable is 2
 ............................

Mais conteúdo relacionado

Mais procurados

My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)aeden_brines
 
Looping statement
Looping statementLooping statement
Looping statementilakkiya
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueJames Thompson
 
PHP 7.0 new features (and new interpreter)
PHP 7.0 new features (and new interpreter)PHP 7.0 new features (and new interpreter)
PHP 7.0 new features (and new interpreter)Andrea Telatin
 
Practiceproblems(1)
Practiceproblems(1)Practiceproblems(1)
Practiceproblems(1)Sena Nama
 
Spf Chapter4 Variables
Spf Chapter4 VariablesSpf Chapter4 Variables
Spf Chapter4 VariablesHock Leng PUAH
 
F# Eye For The C# Guy - f(by) Minsk 2014
F# Eye For The C# Guy - f(by) Minsk 2014F# Eye For The C# Guy - f(by) Minsk 2014
F# Eye For The C# Guy - f(by) Minsk 2014Phillip Trelford
 
Illicium: Compiling Pharo to C
Illicium: Compiling Pharo to CIllicium: Compiling Pharo to C
Illicium: Compiling Pharo to CESUG
 
Symfony tagged services
Symfony tagged servicesSymfony tagged services
Symfony tagged servicesalinalexandru
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to RubyRanjith Siji
 
Looping statement in vb.net
Looping statement in vb.netLooping statement in vb.net
Looping statement in vb.netilakkiya
 
Control Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, StructuresControl Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, Structuresindra Kishor
 

Mais procurados (20)

My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)
 
Ruby.new @ VilniusRB
Ruby.new @ VilniusRBRuby.new @ VilniusRB
Ruby.new @ VilniusRB
 
Looping statement
Looping statementLooping statement
Looping statement
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a Rescue
 
C++ quik notes
C++ quik notesC++ quik notes
C++ quik notes
 
Scripting ppt
Scripting pptScripting ppt
Scripting ppt
 
Defer, Panic, Recover
Defer, Panic, RecoverDefer, Panic, Recover
Defer, Panic, Recover
 
Vb script tutorial
Vb script tutorialVb script tutorial
Vb script tutorial
 
PHP 7.0 new features (and new interpreter)
PHP 7.0 new features (and new interpreter)PHP 7.0 new features (and new interpreter)
PHP 7.0 new features (and new interpreter)
 
Practiceproblems(1)
Practiceproblems(1)Practiceproblems(1)
Practiceproblems(1)
 
Chapter7
Chapter7Chapter7
Chapter7
 
Spf Chapter4 Variables
Spf Chapter4 VariablesSpf Chapter4 Variables
Spf Chapter4 Variables
 
Loops in JavaScript
Loops in JavaScriptLoops in JavaScript
Loops in JavaScript
 
F# Eye For The C# Guy - f(by) Minsk 2014
F# Eye For The C# Guy - f(by) Minsk 2014F# Eye For The C# Guy - f(by) Minsk 2014
F# Eye For The C# Guy - f(by) Minsk 2014
 
Illicium: Compiling Pharo to C
Illicium: Compiling Pharo to CIllicium: Compiling Pharo to C
Illicium: Compiling Pharo to C
 
Symfony tagged services
Symfony tagged servicesSymfony tagged services
Symfony tagged services
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Looping statement in vb.net
Looping statement in vb.netLooping statement in vb.net
Looping statement in vb.net
 
While and For Loops
While and For LoopsWhile and For Loops
While and For Loops
 
Control Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, StructuresControl Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, Structures
 

Destaque

Illuminated By A Course In Miracles
Illuminated By A Course In MiraclesIlluminated By A Course In Miracles
Illuminated By A Course In Miraclesweissillffgtqtu
 
An analysis of economic efficiency in bean production evidence from eastern u...
An analysis of economic efficiency in bean production evidence from eastern u...An analysis of economic efficiency in bean production evidence from eastern u...
An analysis of economic efficiency in bean production evidence from eastern u...Alexander Decker
 
Community Building in Libraries: Success for Every user
Community Building in Libraries: Success for Every userCommunity Building in Libraries: Success for Every user
Community Building in Libraries: Success for Every usersuttonls
 
ZSRx: The Back Story
ZSRx: The Back StoryZSRx: The Back Story
ZSRx: The Back Storysuttonls
 
El desempleo ies pardaiña
El desempleo ies pardaiñaEl desempleo ies pardaiña
El desempleo ies pardaiñasilamora4
 

Destaque (7)

Illuminated By A Course In Miracles
Illuminated By A Course In MiraclesIlluminated By A Course In Miracles
Illuminated By A Course In Miracles
 
Aula 1
Aula 1Aula 1
Aula 1
 
An analysis of economic efficiency in bean production evidence from eastern u...
An analysis of economic efficiency in bean production evidence from eastern u...An analysis of economic efficiency in bean production evidence from eastern u...
An analysis of economic efficiency in bean production evidence from eastern u...
 
Community Building in Libraries: Success for Every user
Community Building in Libraries: Success for Every userCommunity Building in Libraries: Success for Every user
Community Building in Libraries: Success for Every user
 
ZSRx: The Back Story
ZSRx: The Back StoryZSRx: The Back Story
ZSRx: The Back Story
 
Ruby Hell Yeah
Ruby Hell YeahRuby Hell Yeah
Ruby Hell Yeah
 
El desempleo ies pardaiña
El desempleo ies pardaiñaEl desempleo ies pardaiña
El desempleo ies pardaiña
 

Semelhante a 10 ruby loops

Blocks and loops.pptx
Blocks and loops.pptxBlocks and loops.pptx
Blocks and loops.pptxsandeep kumar
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Wen-Tien Chang
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technologyppparthpatel123
 
Case, Loop & Command line args un Unix
Case, Loop & Command line args un UnixCase, Loop & Command line args un Unix
Case, Loop & Command line args un UnixVpmv
 
Linux System Administration
Linux System AdministrationLinux System Administration
Linux System AdministrationJayant Dalvi
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# DevelopersCory Foy
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfranjanadeore1
 
Licão 12 decision loops - statement iteration
Licão 12 decision loops - statement iterationLicão 12 decision loops - statement iteration
Licão 12 decision loops - statement iterationAcácio Oliveira
 
CPAP.com Introduction To Coding: Part 2
CPAP.com Introduction To Coding: Part 2CPAP.com Introduction To Coding: Part 2
CPAP.com Introduction To Coding: Part 2johnnygoodman
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingChaAstillas
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingaprilyyy
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyLarry Diehl
 

Semelhante a 10 ruby loops (20)

09 ruby if else
09 ruby if else09 ruby if else
09 ruby if else
 
Blocks and loops.pptx
Blocks and loops.pptxBlocks and loops.pptx
Blocks and loops.pptx
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Case, Loop & Command line args un Unix
Case, Loop & Command line args un UnixCase, Loop & Command line args un Unix
Case, Loop & Command line args un Unix
 
Linux System Administration
Linux System AdministrationLinux System Administration
Linux System Administration
 
Iq rails
Iq railsIq rails
Iq rails
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdf
 
Licão 12 decision loops - statement iteration
Licão 12 decision loops - statement iterationLicão 12 decision loops - statement iteration
Licão 12 decision loops - statement iteration
 
CPAP.com Introduction To Coding: Part 2
CPAP.com Introduction To Coding: Part 2CPAP.com Introduction To Coding: Part 2
CPAP.com Introduction To Coding: Part 2
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Ruby
RubyRuby
Ruby
 
00 ruby tutorial
00 ruby tutorial00 ruby tutorial
00 ruby tutorial
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
 

Mais de Walker Maidana (19)

20 ruby input output
20 ruby input output20 ruby input output
20 ruby input output
 
19 ruby iterators
19 ruby iterators19 ruby iterators
19 ruby iterators
 
18 ruby ranges
18 ruby ranges18 ruby ranges
18 ruby ranges
 
17 ruby date time
17 ruby date time17 ruby date time
17 ruby date time
 
16 ruby hashes
16 ruby hashes16 ruby hashes
16 ruby hashes
 
15 ruby arrays
15 ruby arrays15 ruby arrays
15 ruby arrays
 
14 ruby strings
14 ruby strings14 ruby strings
14 ruby strings
 
13 ruby modules
13 ruby modules13 ruby modules
13 ruby modules
 
12 ruby blocks
12 ruby blocks12 ruby blocks
12 ruby blocks
 
11 ruby methods
11 ruby methods11 ruby methods
11 ruby methods
 
08 ruby comments
08 ruby comments08 ruby comments
08 ruby comments
 
07 ruby operators
07 ruby operators07 ruby operators
07 ruby operators
 
06 ruby variables
06 ruby variables06 ruby variables
06 ruby variables
 
05 ruby classes
05 ruby classes05 ruby classes
05 ruby classes
 
03 ruby environment
03 ruby environment03 ruby environment
03 ruby environment
 
01 index
01 index01 index
01 index
 
02 ruby overview
02 ruby overview02 ruby overview
02 ruby overview
 
21 ruby exceptions
21 ruby exceptions21 ruby exceptions
21 ruby exceptions
 
Tutorial ruby eustaquio taq rangel
Tutorial ruby   eustaquio taq rangelTutorial ruby   eustaquio taq rangel
Tutorial ruby eustaquio taq rangel
 

10 ruby loops

  • 1. RUBY LOOPS - WHILE, FOR, UNTIL, BREAK, REDO AND RETRY http://www.tutorialspoint.com/ruby/ruby_loops.htm Copyright © tutorialspoint.com Loops in Ruby are used to execute the same block of code a specified number of times. This chapter details all the loop statements supported by Ruby. Ruby while Statement: Syntax: while conditional [do] code end Executes code while conditional is true. A while loop's conditional is separated from code by the reserved word do, a newline, backslash , or a semicolon ;. Example: #!/usr/bin/ruby $i = 0 $num = 5 while $i < $num do puts("Inside the loop i = #$i" ) $i +=1 end This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4 Ruby while modifier: Syntax: code while condition OR begin code end while conditional Executes code while conditional is true. If a while modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated. Example: #!/usr/bin/ruby
  • 2. $i = 0 $num = 5 begin puts("Inside the loop i = #$i" ) $i +=1 end while $i < $num This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4 Ruby until Statement: until conditional [do] code end Executes code while conditional is false. An until statement's conditional is separated from code by the reserved word do, a newline, or a semicolon. Example: #!/usr/bin/ruby $i = 0 $num = 5 until $i > $num do puts("Inside the loop i = #$i" ) $i +=1; end This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4 Inside the loop i = 5 Ruby until modifier: Syntax: code until conditional OR begin code end until conditional Executes code while conditional is false. If an until modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated.
  • 3. Example: #!/usr/bin/ruby $i = 0 $num = 5 begin puts("Inside the loop i = #$i" ) $i +=1; end until $i > $num This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4 Inside the loop i = 5 Ruby for Statement: Syntax: for variable [, variable ...] in expression [do] code end Executes code once for each element in expression. Example: #!/usr/bin/ruby for i in 0..5 puts "Value of local variable is #{i}" end Here we have defined the range 0..5. The statement for i in 0..5 will allow i to take values in the range from 0 to 5 (including 5).This will produce following result: Value of local variable is 0 Value of local variable is 1 Value of local variable is 2 Value of local variable is 3 Value of local variable is 4 Value of local variable is 5 A for...in loop is almost exactly equivalent to: (expression).each do |variable[, variable...]| code end except that a for loop doesn't create a new scope for local variables. A for loop's expression is separated from code by the reserved word do, a newline, or a semicolon. Example: #!/usr/bin/ruby (0..5).each do |i| puts "Value of local variable is #{i}"
  • 4. end This will produce following result: Value of local variable is 0 Value of local variable is 1 Value of local variable is 2 Value of local variable is 3 Value of local variable is 4 Value of local variable is 5 Ruby break Statement: Syntax: break Terminates the most internal loop. Terminates a method with an associated block if called within the block (with the method returning nil). Example: #!/usr/bin/ruby for i in 0..5 if i > 2 then break end puts "Value of local variable is #{i}" end This will produce following result: Value of local variable is 0 Value of local variable is 1 Value of local variable is 2 Ruby next Statement: Syntax: next Jumps to next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil). Example: #!/usr/bin/ruby for i in 0..5 if i < 2 then next end puts "Value of local variable is #{i}" end This will produce following result: Value of local variable is 2
  • 5. Value of local variable is 3 Value of local variable is 4 Value of local variable is 5 Ruby redo Statement: Syntax: redo Restarts this iteration of the most internal loop, without checking loop condition. Restarts yield or call if called within a block. Example: #!/usr/bin/ruby for i in 0..5 if i < 2 then puts "Value of local variable is #{i}" redo end end This will produce following result and will go in an infinite loop: Value of local variable is 0 Value of local variable is 0 ............................ Ruby retry Statement: Syntax: retry If retry appears in rescue clause of begin expression, restart from the beginning of the 1begin body. begin do_something # exception raised rescue # handles error retry # restart from beginning end If retry appears in the iterator, the block, or the body of the for expression, restarts the invocation of the iterator call. Arguments to the iterator is re-evaluated. for i in 1..5 retry if some_condition # restart from i == 1 end Example: #!/usr/bin/ruby for i in 1..5 retry if i > 2 puts "Value of local variable is #{i}" end
  • 6. This will produce following result and will go in an infinite loop: Value of local variable is 1 Value of local variable is 2 Value of local variable is 1 Value of local variable is 2 Value of local variable is 1 Value of local variable is 2 ............................