Is there a `pipe` equivalent in ruby?

前端 未结 3 1834
甜味超标
甜味超标 2020-12-11 17:12

Occasionally when writing Ruby I find myself wanting a pipe method, similar to tap but returning the result of calling the block with

3条回答
  •  情书的邮戳
    2020-12-11 18:02

    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 usually mentions that abstraction in his posts, he calls it into.

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

提交回复
热议问题