The best Ruby Block Tutorial In 2024, In this tutorial you can learn grammar,yieldstatement,Blocks and methods,BEGIN and END blocks,
You already know how to define a Ruby method and how you call the method. Similarly, Ruby has the concept of a block.
block_name{ statement1 statement2 /en/en/en/en/en }
Here you will learn how to use a simpleyieldstatement to call the block. You will also learn how to use theyieldstatement with parameters to the called block. In the example, you will see two types ofyieldstatement.
Let's look at an example yield statement:
#!/usr/bin/ruby # -*- coding: UTF-8 -*- def test puts "在 test 方法内" yield puts "你又回到了 test 方法内" yield end test {puts "你在块内"}
Examples of the above operating results as follows:
在 test 方法内 你在块内 你又回到了 test 方法内 你在块内
You can also pass yield statement with parameters. Here is an example:
#!/usr/bin/ruby # -*- coding: UTF-8 -*- def test yield 5 puts "在 test 方法内" yield 100 end test {|i| puts "你在块 #{i} 内"}
Examples of the above operating results as follows:
你在块 5 内 在 test 方法内 你在块 100 内
Here, after theyieldstatement followed parameters. You can even pass multiple parameters. In the block, you can place a variable between two vertical bars to accept the parameters. Thus, in the above code, yield 5 statement is passed as a parameter to the value of 5 test pieces.
Now, look at the following statement:
test {|i| puts "你在块 #{i} 内"}
Here, the value of 5 will receive the variable i. Now, we put observe the following statement:
puts "你在块 #{i} 内"
This puts the output statement is:
你在块 5 内
If you want to pass multiple parameters, then theyieldstatement is as follows:
yield a, b
At this time, as shown in the block:
test {|a, b| statement}
Parameters separated by commas.
You have seen between the block and the method of how interrelated. You typically use the yield statement calls the block from the method having the same name. Therefore, the code is as follows:
#!/usr/bin/ruby def test yield end test{ puts "Hello world"}
This example is the simplest way to achieve the block. You use theyieldstatement calls the test block.
But if the last parameter before the method with & then you can the method is passed a block, and this block may be assigned to the last parameter. If the * and & also appear in the parameter list, & should be placed on the back.
#!/usr/bin/ruby def test(&block) block.call end test { puts "Hello World!"}
Examples of the above operating results as follows:
Hello World!
Every Ruby source file can declare when code blocks (BEGIN block) when the file is loaded to run, and after the program finishes executing code blocks to run (END block).
#!/usr/bin/ruby BEGIN { # BEGIN 代码块 puts "BEGIN 代码块" } END { # END 代码块 puts "END 代码块" } # MAIN 代码块 puts "MAIN 代码块"
A program can contain multiple BEGIN and END blocks. BEGIN block is executed in the order in which they appear. END blocks as they appear in reverse order. When executed, the above program produces the following results:
BEGIN 代码块 MAIN 代码块 END 代码块