Is there a `pipe` equivalent in ruby?

前端 未结 3 1828
甜味超标
甜味超标 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 17:54

    Ruby 2.5 introduced Object.yield_self which is exactly the pipe operator you're using: it receives a block, passes self as the first argument to it and returns the result of evaluating the block.

    class Object
      def yield_self(*args)
        yield(self, *args)
      end
    end
    

    Example usage:

    "Hello".yield_self { |str| str + " World" }
    # Returns "Hello World"
    

    You can also read a little more about it in the following blog posts:

    1. Explains the difference with Rails' try and Ruby's tap methods
    2. Some very nice examples of using yield_self to simplify code

提交回复
热议问题