您已经看到Ruby如何定义可以放置语句数量然后调用该方法的方法.类似地,Ruby有一个Block概念.
一个块由代码块组成.
为块指定名称.
块中的代码始终包含在大括号内({} ).
总是从一个与块名称相同的函数调用一个块.这意味着如果你有一个名为 test 的块,那么你使用函数 test 来调用这个块.
使用 yield 语句调用块.
block_name { statement1 statement2 .......... }
在这里,您将学习使用简单的 yield 语句调用块.您还将学习使用带有参数的 yield 语句来调用块.您将使用两种类型的 yield 语句检查示例代码.
让我们看一个示例屈服声明 :
#!/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"}
这将产生以下结果 :
You are in the method You are in the block You are again back to the method You are in the block
您还可以使用yield语句传递参数.以下是一个示例 :
#!/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}"}
这将产生以下结果 :
You are in the block 5 You are in the method test You are in the block 100
这里,写入 yield 语句后跟参数.您甚至可以传递多个参数.在块中,将变量放在两条垂直线(||)之间以接受参数.因此,在前面的代码中,yield 5语句将值5作为参数传递给测试块.
现在,查看以下语句 :
test {|i| puts "You are in the block #{i}"}
这里,值变量 i 中接收值5.现在,观察以下 puts 语句 :
puts "You are in the block #{i}"
此 puts 语句的输出为 :
You are in the block 5
如果要传递多个参数,则 yield 语句将变为 :
yield a, b
且该块为&减去;
test {|a, b| statement}
参数将用逗号分隔.
您已经了解了块和方法如何相互关联.您通常使用与块的名称相同的方法使用yield语句来调用块.因此,你写 :
#!/usr/bin/ruby def test yield end test{ puts "Hello world"}
这个例子是实现块的最简单方法.您可以使用 yield 语句调用测试块.
但是如果方法的最后一个参数前面是&,那么您可以传递一个块到此方法和此块将分配给最后一个参数.如果*和&存在于参数列表中,&应该晚一点.
#!/usr/bin/ruby def test(&block) block.call end test { puts "Hello World!"}
这将产生以下结果结果 :
Hello World!
每个Ruby源文件都可以声明要在文件运行时运行的代码块加载(BEGIN块)并在程序执行完毕后(END块).
#!/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"
程序可能包含多个BEGIN和END块. BEGIN块按它们遇到的顺序执行. END块以相反的顺序执行.执行时,上述程序产生以下结果 :
BEGIN code block MAIN code block END code block