偶尔写Ruby的时候,我发现自己想一个pipe方法,类似于tap但返回的结果与调用块self作为参数,就像这样:
class Object
def pipe(&block)
block.call(self)
end
end
some_operation.pipe { |x| some_other_operation(x) }
Run Code Online (Sandbox Code Playgroud)
..但到目前为止,我还没有设法找出它的名称,如果存在的话.它存在吗?
如果没有,我知道我可以通过猴子补丁来添加它,但是,你知道,这很糟糕.除非有一个辉煌的,保证永不冲突(和描述性和简短)的名称,我可以用它...
tok*_*and 12
这种抽象在核心中不存在.我通常称之为as,它很简短并且是声明性的:
class Object
def as
yield(self)
end
end
"3".to_i.as { |x| x*x } #=> 9
Run Code Online (Sandbox Code Playgroud)
所以,总结起来,一些名字:pipe,as,into,peg,thru.
| 归档时间: |
|
| 查看次数: |
446 次 |
| 最近记录: |