Ruby 编程中的 yield 关键词
在很多情况下,我们希望在方法中多次执行常规表达式,但无需反复书写同一表达式。通过 yield 关键字可以做到这一点。
我们还可以向 yield 关键字传递参数,并获得返回值。现在,我们来看一些示例,了解 Ruby 中的 yield 关键字如何工作。
示例 1
考虑下面所示的代码,我们在其中在方法内部声明了两个常规 yield 关键字,然后调用它。
def tuts
puts "In the tuts method"
# using yield keyword
yield
puts "Again back to the tuts method"
yield
end
tuts {puts "Yield executed!"}输出
它将生成以下输出 -
In the tuts method Yield executed! Again back to the tuts method Yield executed!
示例 2
现在,我们尝试在 yield 关键字中添加参数。考虑下面所示的代码。
def tuts
yield 2*5
puts "In the method tuts"
yield 150
end
tuts {|i| puts "yield #{i}"}输出
如果我们在任何 Ruby IDE 上编写以下代码,那么在终端中将获得以下输出。
yield 10 In the method tuts yield 150
示例 3
现在,我们来看一个示例,其中我们将从 Ruby 中的 yield 返回值。考虑下面所示的代码。
def return_value_yield
tutorials_point = yield
puts tutorials_point
end
return_value_yield { "Welcome to TutorialsPoint" }输出
如果我们在任何 Ruby IDE 上编写以下代码,那么在终端中将获得以下输出。
Welcome to TutorialsPoint
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP