SlideShare una empresa de Scribd logo
1 de 3
Descargar para leer sin conexión
RUBY BLOCKS
http://www.tutorialspoint.com/ruby/ruby_blocks.htm                                             Copyright © tutorialspoint.com



You have seen how Ruby defines methods where you can put number of statements and then you call that method.
Similarly Ruby has a concept of Bolck.

       A block consists of chunks of code.

       You assign a name to a block.

       The code in the block is always enclosed within braces ({}).

       A block is always invoked from a function with the same name as that of the block. This means that if you have
       a block with the name test, then you use the function test to invoke this block.

       You invoke a block by using the yield statement.

Syntax:

 block_name{
    statement1
    statement2
    ..........
 }


Here you will learn to invoke a block by using a simple yield statement. You will also learn to use a yield statement
with parameters for invoking a block. You will check the sample code with both types of yield statements.

The yield Statement:

Let.s look at an example of the yield statement:

 #!/usr/bin/ruby

 def test
    puts "You are in the method"
    yield
    puts "You are again back to the method"
    yield
 end
 test {puts "You are in the block"}


This will produce following result:

 You   are   in the method
 You   are   in the block
 You   are   again back to the method
 You   are   in the block


You also can pass parameters with the yield statement. Here is an example:

 #!/usr/bin/ruby

 def test
    yield 5
    puts "You are in the method test"
    yield 100
 end
 test {|i| puts "You are in the block #{i}"}
This will produce following result:

 You are in the block 5
 You are in the method test
 You are in the block 100


Here the yield statement is written followed by parameters. You can even pass more than one parameter. In the block,
you place a variable between two vertical lines (||) to accept the parameters. Therefore, in the preceding code, the yield
5 statement passes the value 5 as a parameter to the test block.

Now look at the following statement:

 test {|i| puts "You are in the block #{i}"}


Here the value 5 is received in the variable i. Now observe the following puts statement:

 puts "You are in the block #{i}"


The output of this puts statement is:

 You are in the block 5


If you want to pass more than one parameters, then the yield statement becomes:

 yield a, b


and the block is:

 test {|a, b| statement}


The parameters will be separated by commas.

Blocks and Methods:

You have seen how how a block and a method can be associated with each other.You normally invoke a block by using
the yield statement from a method that has the same name as that of the block. Therefore, you write:

 def test
   yield
 end
 test{ puts "Hello world"}


This example is the simplest way to implement a block.You call the test block by using the yield statement.

But if the last argument of a method is preceded by &, then you can pass a block to this method and this block will be
assigned to the last parameter. In case both * and & are present in the argument list, & should come later.

 def test(&block)
    block.call
 end
 test { puts "Hello World!"}


This will produce following result:

 Hello World!


BEGIN and END Blocks
Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the
program has finished executing (the END blocks).

 BEGIN {
    begin block code
 }

 END {
    end block code
 }


A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are
encountered. END blocks are executed in reverse order.

Más contenido relacionado

La actualidad más candente

Unit testing.pptx [repaired]
Unit testing.pptx [repaired]Unit testing.pptx [repaired]
Unit testing.pptx [repaired]Mohammad Asmar
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutesRay Toal
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Presentation on Template Method Design Pattern
Presentation on Template Method Design PatternPresentation on Template Method Design Pattern
Presentation on Template Method Design PatternAsif Tayef
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in javajunnubabu
 
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2Katy Slemon
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in pythonjunnubabu
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 

La actualidad más candente (20)

Unit testing.pptx [repaired]
Unit testing.pptx [repaired]Unit testing.pptx [repaired]
Unit testing.pptx [repaired]
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutes
 
string tokenization
string tokenizationstring tokenization
string tokenization
 
02 - Prepcode
02 - Prepcode02 - Prepcode
02 - Prepcode
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Vbscript
VbscriptVbscript
Vbscript
 
Loops in java script
Loops in java scriptLoops in java script
Loops in java script
 
Presentation on Template Method Design Pattern
Presentation on Template Method Design PatternPresentation on Template Method Design Pattern
Presentation on Template Method Design Pattern
 
Loops in JavaScript
Loops in JavaScriptLoops in JavaScript
Loops in JavaScript
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
 
Php unit
Php unitPhp unit
Php unit
 
Introduction to Preprocessors
Introduction to PreprocessorsIntroduction to Preprocessors
Introduction to Preprocessors
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
22 multi threading iv
22 multi threading iv22 multi threading iv
22 multi threading iv
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 

Destacado

Epigramas Americanos Enrique DíEz Canedo
Epigramas Americanos Enrique DíEz CanedoEpigramas Americanos Enrique DíEz Canedo
Epigramas Americanos Enrique DíEz CanedoFelipe Leal Bravo
 
Trabajo final diseno_de_proyectos
Trabajo final diseno_de_proyectosTrabajo final diseno_de_proyectos
Trabajo final diseno_de_proyectosJuan Pablo Cortes
 
Leadcom profile 2014
Leadcom profile 2014Leadcom profile 2014
Leadcom profile 2014Fion Liang
 
Track pp-noviembre-s2-n44-vf
Track pp-noviembre-s2-n44-vfTrack pp-noviembre-s2-n44-vf
Track pp-noviembre-s2-n44-vfLa Nacion Chile
 
Group15 narsimhacommitteereportonfinancialreforms-
Group15 narsimhacommitteereportonfinancialreforms-Group15 narsimhacommitteereportonfinancialreforms-
Group15 narsimhacommitteereportonfinancialreforms-sksbatish
 
El telefono, la prensa y la television
El telefono, la prensa y la televisionEl telefono, la prensa y la television
El telefono, la prensa y la televisionArturo Salmoran Garcia
 
Elit 48 c class 18 post qhq
Elit 48 c class 18 post qhqElit 48 c class 18 post qhq
Elit 48 c class 18 post qhqjordanlachance
 
Diapos prop intelectual expo
Diapos prop intelectual expoDiapos prop intelectual expo
Diapos prop intelectual expoROSAUDEPI
 
Q6. Evaluation.
Q6. Evaluation.Q6. Evaluation.
Q6. Evaluation.karleab
 
Parent graphs
Parent graphs Parent graphs
Parent graphs tschmucker
 
Novo e-pay
Novo e-payNovo e-pay
Novo e-payEvaBF
 
Plànol del circuit (general)
Plànol del circuit (general)Plànol del circuit (general)
Plànol del circuit (general)Ivan C.
 
自殺幇助の是非
自殺幇助の是非自殺幇助の是非
自殺幇助の是非Erika Abe
 

Destacado (20)

Variables
VariablesVariables
Variables
 
Epigramas Americanos Enrique DíEz Canedo
Epigramas Americanos Enrique DíEz CanedoEpigramas Americanos Enrique DíEz Canedo
Epigramas Americanos Enrique DíEz Canedo
 
Trabajo final diseno_de_proyectos
Trabajo final diseno_de_proyectosTrabajo final diseno_de_proyectos
Trabajo final diseno_de_proyectos
 
Leadcom profile 2014
Leadcom profile 2014Leadcom profile 2014
Leadcom profile 2014
 
Track pp-noviembre-s2-n44-vf
Track pp-noviembre-s2-n44-vfTrack pp-noviembre-s2-n44-vf
Track pp-noviembre-s2-n44-vf
 
I wish you..
I wish you..I wish you..
I wish you..
 
Group15 narsimhacommitteereportonfinancialreforms-
Group15 narsimhacommitteereportonfinancialreforms-Group15 narsimhacommitteereportonfinancialreforms-
Group15 narsimhacommitteereportonfinancialreforms-
 
Cyber
CyberCyber
Cyber
 
Lo cotidiano. pptx
Lo cotidiano. pptxLo cotidiano. pptx
Lo cotidiano. pptx
 
El telefono, la prensa y la television
El telefono, la prensa y la televisionEl telefono, la prensa y la television
El telefono, la prensa y la television
 
Messages
MessagesMessages
Messages
 
messager
 messager messager
messager
 
Elit 48 c class 18 post qhq
Elit 48 c class 18 post qhqElit 48 c class 18 post qhq
Elit 48 c class 18 post qhq
 
Diapos prop intelectual expo
Diapos prop intelectual expoDiapos prop intelectual expo
Diapos prop intelectual expo
 
Q6. Evaluation.
Q6. Evaluation.Q6. Evaluation.
Q6. Evaluation.
 
Parent graphs
Parent graphs Parent graphs
Parent graphs
 
Novo e-pay
Novo e-payNovo e-pay
Novo e-pay
 
Plànol del circuit (general)
Plànol del circuit (general)Plànol del circuit (general)
Plànol del circuit (general)
 
Presentación1 hjgh
Presentación1 hjghPresentación1 hjgh
Presentación1 hjgh
 
自殺幇助の是非
自殺幇助の是非自殺幇助の是非
自殺幇助の是非
 

Similar a 12 ruby blocks

MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxVeerannaKotagi1
 
Variables in MIT App Inventor powerpoint
Variables in MIT App Inventor powerpointVariables in MIT App Inventor powerpoint
Variables in MIT App Inventor powerpointJohnLagman3
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# DevelopersCory Foy
 
Ruby basics || updated
Ruby basics || updatedRuby basics || updated
Ruby basics || updateddatt30
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfranjanadeore1
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84Mahmoud Samir Fayed
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldYura Nosenko
 
The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185Mahmoud Samir Fayed
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 

Similar a 12 ruby blocks (20)

Ruby Blocks
Ruby BlocksRuby Blocks
Ruby Blocks
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
 
Variables in MIT App Inventor powerpoint
Variables in MIT App Inventor powerpointVariables in MIT App Inventor powerpoint
Variables in MIT App Inventor powerpoint
 
11 ruby methods
11 ruby methods11 ruby methods
11 ruby methods
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
 
Rspec 101
Rspec 101Rspec 101
Rspec 101
 
Ruby basics || updated
Ruby basics || updatedRuby basics || updated
Ruby basics || updated
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdf
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 world
 
Inheritance
InheritanceInheritance
Inheritance
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180
 
Ruby Blocks
Ruby BlocksRuby Blocks
Ruby Blocks
 
The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 

Más de Walker Maidana (20)

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
 
10 ruby loops
10 ruby loops10 ruby loops
10 ruby loops
 
09 ruby if else
09 ruby if else09 ruby if else
09 ruby if else
 
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
 
04 ruby syntax
04 ruby syntax04 ruby syntax
04 ruby syntax
 
03 ruby environment
03 ruby environment03 ruby environment
03 ruby environment
 
01 index
01 index01 index
01 index
 
00 ruby tutorial
00 ruby tutorial00 ruby tutorial
00 ruby tutorial
 
02 ruby overview
02 ruby overview02 ruby overview
02 ruby overview
 
21 ruby exceptions
21 ruby exceptions21 ruby exceptions
21 ruby exceptions
 

12 ruby blocks

  • 1. RUBY BLOCKS http://www.tutorialspoint.com/ruby/ruby_blocks.htm Copyright © tutorialspoint.com You have seen how Ruby defines methods where you can put number of statements and then you call that method. Similarly Ruby has a concept of Bolck. A block consists of chunks of code. You assign a name to a block. The code in the block is always enclosed within braces ({}). A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the name test, then you use the function test to invoke this block. You invoke a block by using the yield statement. Syntax: block_name{ statement1 statement2 .......... } Here you will learn to invoke a block by using a simple yield statement. You will also learn to use a yield statement with parameters for invoking a block. You will check the sample code with both types of yield statements. The yield Statement: Let.s look at an example of the yield statement: #!/usr/bin/ruby def test puts "You are in the method" yield puts "You are again back to the method" yield end test {puts "You are in the block"} This will produce following result: You are in the method You are in the block You are again back to the method You are in the block You also can pass parameters with the yield statement. Here is an example: #!/usr/bin/ruby def test yield 5 puts "You are in the method test" yield 100 end test {|i| puts "You are in the block #{i}"}
  • 2. This will produce following result: You are in the block 5 You are in the method test You are in the block 100 Here the yield statement is written followed by parameters. You can even pass more than one parameter. In the block, you place a variable between two vertical lines (||) to accept the parameters. Therefore, in the preceding code, the yield 5 statement passes the value 5 as a parameter to the test block. Now look at the following statement: test {|i| puts "You are in the block #{i}"} Here the value 5 is received in the variable i. Now observe the following puts statement: puts "You are in the block #{i}" The output of this puts statement is: You are in the block 5 If you want to pass more than one parameters, then the yield statement becomes: yield a, b and the block is: test {|a, b| statement} The parameters will be separated by commas. Blocks and Methods: You have seen how how a block and a method can be associated with each other.You normally invoke a block by using the yield statement from a method that has the same name as that of the block. Therefore, you write: def test yield end test{ puts "Hello world"} This example is the simplest way to implement a block.You call the test block by using the yield statement. But if the last argument of a method is preceded by &, then you can pass a block to this method and this block will be assigned to the last parameter. In case both * and & are present in the argument list, & should come later. def test(&block) block.call end test { puts "Hello World!"} This will produce following result: Hello World! BEGIN and END Blocks
  • 3. Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks). BEGIN { begin block code } END { end block code } A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order.