May 12, 2021 Ruby
You already know how Ruby defines methods and how you call them. Similarly, Ruby has a block concept.
block_name{ statement1 statement2 .......... }
Here you'll learn how to use a simple yield statement to call a block. Y ou'll also learn how to call blocks using yield statements with parameters. In the instance, you'll see both types of yield statements.
Let's look at an example of a yield statement:
#!/usr/bin/ruby # -*- coding: UTF-8 -*- def test puts "在 test 方法内" yield puts "你又回到了 test 方法内" yield end test {puts "你在块内"}
This results in the following:
在 test 方法内 你在块内 你又回到了 test 方法内 你在块内
You can also pass a yield statement with arguments. Here's an example:
#!/usr/bin/ruby # -*- coding: UTF-8 -*- def test yield 5 puts "在 test 方法内" yield 100 end test {|i| puts "你在块 #{i} 内"}
This results in the following:
你在块 5 内 在 test 方法内 你在块 100 内
Here, the yield statement is followed by the argument. Y ou can even pass multiple parameters. I n a block, you can place a variable between two verticals to accept arguments. Therefore, in the code above, the yield 5 statement passes a value of 5 as an argument to the test block.
Now, look at the following statement:
test {|i| puts "你在块 #{i} 内"}
Here, the value 5 is received in variable i. Now, look at the puts statement below:
puts "你在块 #{i} 内"
The output of this puts statement is:
你在块 5 内
If you want to pass more than one argument, the yield statement looks like this:
yield a, b
At this point, the block looks like this:
test {|a, b| statement}
Arguments are separated by commas.
You've seen how blocks and methods are related to each other. Y ou typically use the yield statement to call blocks from methods that have the same name as them. Therefore, the code looks like this:
#!/usr/bin/ruby def test yield end test{ puts "Hello world"}
This example is the easiest way to implement blocks. You use the yield statement to call the test block.
However, if the last argument of a method is fronted by a block, you can pass a block to the method that can be assigned to the last argument. If both the and the and the parameters appear in the list, they should be placed after it.
#!/usr/bin/ruby def test(&block) block.call end test { puts "Hello World!"}Try it out . . .
This results in the following:
Hello World!
Each Ruby source file can declare the block of code (BEGIN block) to run when the file is loaded, and the block of code (END block) to run after the program is executed.
#!/usr/bin/ruby BEGIN { # BEGIN 代码块 puts "BEGIN 代码块" } END { # END 代码块 puts "END 代码块" } # MAIN 代码块 puts "MAIN 代码块"
A program can contain multiple BEGIN and END blocks. B EGIN blocks are executed in the order in which they appear. E ND blocks are executed in the reverse order in which they occur. When executed, the above program produces the following results:
BEGIN 代码块 MAIN 代码块 END 代码块