Ruby - Blocks块

Ruby - Blocks块 首页 / Ruby入门教程 / Ruby - Blocks块

您已经了解了Ruby是如何定义方法的,可以在其中放置大量语句,然后调用该方法。同样,Ruby也具有Block的概念。

Block 语法

block_name {
   statement1
   statement2
   ..........
}

在这里,您将学习使用简单的 yield 语句来调用块。您还将学习使用带参数的 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}"}

在这里,值5接收在变量 i 中。现在,观察以下 put 语句-

puts "You are in the block #{i}"

该 put 语句的输出为-

You are in the block 5

如果要传递多个参数,则 yield 语句将变为-

yield a, b

并且块是-

test {|a, b| statement}

参数将以逗号分隔。

Blocks 和 Methods

您已经了解了块和方法如何相互关联。通常,您可以通过使用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!

BEGIN 和 END 块

每个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"

一个程序可能包含多个BEGINEND块。 BEGIN块按遇到的顺序执行。 END块以相反的顺序执行。执行后,上述程序会产生以下输出-

BEGIN code block
MAIN code block
END code block

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

左耳听风 -〔陈皓〕

Vue开发实战 -〔唐金州〕

趣谈Linux操作系统 -〔刘超〕

Python核心技术与实战 -〔景霄〕

后端存储实战课 -〔李玥〕

互联网人的英语私教课 -〔陈亦峰〕

容器实战高手课 -〔李程远〕

Tony Bai · Go语言第一课 -〔Tony Bai〕

超级访谈:对话毕玄 -〔毕玄〕

好记忆不如烂笔头。留下您的足迹吧 :)