ruby 中 Kernel#yield_self、yield(self) 和 Object#tap 的区别 [英] Difference between Kernel#yield_self, yield(self) and Object#tap in ruby
问题描述
Ruby 2.5.0-rc1 已经发布,并引入了一个新的 Kernel#yield_self
方法.
Ruby 2.5.0-rc1 has been released and introduces a new Kernel#yield_self
method.
yield_self
、yield(self)
和现有的 Object#tap
方法有什么区别?
What is the difference between yield_self
, yield(self)
and the existing Object#tap
method?
推荐答案
tap
和 yield_self
位于这两种方法中的每一种返回的内容中.
The difference between tap
and yield_self
is in what is returned by each of the two methods.
Object#tap
将 self 交给块 ,然后返回 self.Kernel#yield_self
将 self 交给区块,然后返回区块的结果.
Object#tap
yields self to the block and then returns self. Kernel#yield_self
yields self to the block and then returns the result of the block.
以下是一些示例,说明每种方法都有哪些用处:
Here are some examples of where each can be useful:
替换方法末尾对 result
行的需要:
Replacing the need for a result
line at the end of a method:
def my_method
result = get_some_result
call_some_method_with result
result
end
可以写成:
def my_method
get_some_result.tap do |result|
call_some_method_with result
end
end
另一个例子是一些需要几个步骤的对象的初始化:
Another example is initialisation of some object that takes several steps:
some_object = SomeClass.new.tap do |obj|
obj.field1 = some_value
obj.field2 = other_value
end
yield_self 和 yield(self)
如果在您自己的方法之一中使用 yield_self
将具有与 yield(self)
相同的效果.然而,通过将它作为一个方法本身,这促进了方法链作为嵌套函数调用的替代方法.
yield_self and yield(self)
If used inside one of your own methods yield_self
would have the same effect as yield(self)
. However, by having it as a method in its own right this promotes method chaining as an alternative to nested function calls.
这篇博文 Michał Łomnicki 提供了一些有用的示例.例如这段代码:
This blog post by Michał Łomnicki has some helpful examples. e.g. this code:
CSV.parse(File.read(File.expand_path("data.csv"), __dir__))
.map { |row| row[1].to_i }
.sum
可以改写为:
"data.csv"
.yield_self { |name| File.expand_path(name, __dir__) }
.yield_self { |path| File.read(path) }
.yield_self { |body| CSV.parse(body) }
.map { |row| row[1].to_i }
.sum
这可以帮助清晰地说明嵌套调用用于对某些数据进行一系列转换的位置.其他编程语言中也存在类似的功能.Elixir 中的管道操作符值得一看,
This can aid with clarity where nested calls are being used for a series of transformations on some data. Similar features exist in other programming languages. The pipe operator in Elixir is a good one to take a look at,
这篇关于ruby 中 Kernel#yield_self、yield(self) 和 Object#tap 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!