gpt4 book ai didi

ruby - ruby 中是否有 `pipe` 等价物?

转载 作者:数据小太阳 更新时间:2023-10-29 06:57:11 26 4
gpt4 key购买 nike

偶尔在编写 Ruby 时我发现自己想要一个 pipe 方法,类似于 tap 但返回 result 调用 block self 作为参数,像这样:

class Object
def pipe(&block)
block.call(self)
end
end

some_operation.pipe { |x| some_other_operation(x) }

..但到目前为止我还没有弄清楚它叫什么,如果它存在的话。存在吗?

如果没有,我知道我可以通过 monkey-patch 对象来添加它,但是,你知道,那很糟糕。除非有一个出色的、保证永远不会冲突的(描述性的和简短的)名称,否则我可以使用它...

最佳答案

核心中不存在这种抽象。我通常称它为 as,它简短且具有声明性:

class Object
def as
yield(self)
end
end

"3".to_i.as { |x| x*x } #=> 9

Raganwald通常在他的帖子中提到这个抽象,他称之为 into .

所以,总结一下,一些名称:pipeasintopeg通过

关于ruby - ruby 中是否有 `pipe` 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12848967/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com