Grammar:
block_name{
statement1 statement2 .....
}
Here, you will learn how to call blocks by using a simple yield statement. You will also learn to use the yield statement to have parameter call blocks. The sample code that will be checked, the two types of yield statements.
Yield statement:
Let's take a look at an example in the yield statement:
#!/usr/bin/ruby
def Test
puts "you are the"
yield
puts "are again >yield
End
Test {puts ' you are in ' block}
This will produce the following results:
You are are in the "method" you are in the blocks you
are again the
You can also pass the argument with the yield declaration. Here is an example:
#!/usr/bin/ruby
def Test
yield 5
puts "You are in ' method test"
yield-
end
Test {|i| Puts "You are in the Block #{i}"}
This will produce the following results:
You are are in the "Block 5" are in the "method test" you are in the Block
100
Here the yield statement is written to follow the arguments. You can even pass multiple parameters. The parameter that is received by the variable (| |) that is placed between the two vertical lines in the block. Therefore, in the above code, the YIELD5 statement takes the test block as a parameter value of 5.
Now look at the following statement:
Test {|i| puts ' you are in the ' Block #{i} '}
Here, the value in the variable i is 5. Now observe the following puts statement:
Puts "You are in the Block #{i}"
The output of the puts statement is:
If you want to exceed one argument, then the yield statement becomes:
So the block is:
These parameters are separated by commas.
Blocks and methods:
We've seen how to associate a block with a method. Typically, the call block has a method with the same name from the block by using the yield statement. Therefore, write:
#!/usr/bin/ruby
def Test
yield
end
test{puts "Hello World"}
This example is the simplest way to implement a block. Call block test uses the yield statement.
However, if the last parameter's method is preceded by &, then a block can be used, and this block will be assigned to the last parameter.
* and & in the list of parameters & & is still behind.
#!/usr/bin/ruby
def Test (&block)
block.call
end
test {puts "Hello world!"}
This would produce following result:
Hello world!
BEGIN and End Blocks
After each ruby source file can be declared as a file to be loaded to run (begin block), the program has finished (end block).
#!/usr/bin/ruby
begin {
# begin block Code
puts ' begin code block '
} end
{
# End block Code
puts "end code block"
}
# Main block code
puts ' main code block '
A program may include multiple begin and end blocks. The begin blocks are executed in the order in which they are encountered. End blocks are executed in reverse order. When the above program executes, the following results are produced:
BEGIN code block
MAIN code block end
code block