Ruby block
You already know how Ruby defines methods and how you call methods. Similarly, Ruby has the concept of blocks.
- A block consists of chunks of code.
- You need to give a block a name.
- The code in the block is always enclosed within braces {}.
- Blocks are always called from functions with the same name. This means that if your block name istest, then you would use the functiontestto call this block.
- You can use theyieldstatement to invoke a block.
Syntax
Here, you will learn how to use a simpleyieldstatement to invoke a block. You will also learn how to use ayieldstatement with parameters to invoke a block. In the examples, you will see these two types ofyieldstatements.
yieldStatements
Let's look at an example of a yield statement:
Example
Try it »
The output of the above example is:
在 test 方法内 你在块内 你又回到了 test 方法内 你在块内
You can also pass a yield statement with parameters. Here is an example:
Example
Try it »
The output of the above example is:
你在块 5 内 在 test 方法内 你在块 100 内
Here,yieldthe statement is followed by parameters. You can even pass multiple parameters. In the block, you can place a variable between two vertical bars to accept parameters. Therefore, in the above code, the yield 5 statement passes the value 5 to the test block as a parameter.
Now, look at the following statement:
Here, the value 5 is received in variable i. Now, observe the following puts statement:
The output of this puts statement is:
If you want to pass multiple parameters, thenyieldthe statement looks as follows:
At this point, the block looks as follows:
The parameters are separated by commas.
Blocks and Methods
You have seen how blocks and methods are related to each other. You usually use the yield statement to invoke a block from a method with the same name. Therefore, the code is as follows:
Example
This example is the simplest way to implement a block. You use theyieldstatement to invoke the test block.
However, if the last parameter of a method is preceded by &, then you can pass a block to that method, and this block can be assigned to the last parameter. If * and & appear together in the parameter list, & should be placed after.
The output of the above example is:
Hello World!
BEGIN and END Blocks
Each Ruby source file can declare a block of code to be run when the file is loaded (a BEGIN block), and a block of code to run after the program has finished executing (an END block).
Example
A program can contain multiple BEGIN and END blocks. BEGIN blocks are executed in the order they appear. END blocks are executed in the reverse order they appear. When executed, the above program outputs the following result:
BEGIN 代码块 MAIN 代码块 END 代码块Other Extensions