ruby 中是否有“管道"等价物? [英] Is there a `pipe` equivalent in ruby?

查看:48
本文介绍了ruby 中是否有“管道"等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Occasionally when writing Ruby I find myself wanting a pipe method, similar to tap but returning the result of calling the block with self as a parameter, like this:

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

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

..但到目前为止我还没有找到它的名字,如果它存在的话.存在吗?

..but so far I haven't managed to find out what it's called, if it exists. Does it exist?

如果没有,我知道我可以通过猴子补丁对象来添加它,但是,你知道,这很糟糕.除非有一个绝妙的、保证永远不会冲突的(和描述性的和简短的)名称,否则我可以用它...

If it doesn't, I know I could monkey-patch object to add it but, y'know, that's bad. Unless there's a brilliant, guaranteed to never clash (and descriptive and short) name I could use for it...

推荐答案

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

This abstraction doesn't exist in the core. I usually call it as, it's short and declarative:

class Object
  def as
    yield(self)
  end
end

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

Raganwald 通常在他的帖子中提到这种抽象,他称之为 进入.

Raganwald usually mentions that abstraction in his posts, he calls it into.

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

So, summing it up, some names: pipe, as, into, peg, thru.

这篇关于ruby 中是否有“管道"等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆