Is there a `pipe` equivalent in ruby?

前端 未结 3 1824
甜味超标
甜味超标 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:55

    Here's the the technique I use to chain objects. It's pretty much exactly as above except I don't reopen the Object class. Instead, I create a Module which I will use to extend whatever object instance I'm working with. See below:

    module Chainable
      def as
        (yield self.dup).extend(Chainable)
      end
    end
    

    I've defined this method to prohibit mutative methods from altering the original object. Below is a trivial example of using this module:

    [3] pry(main)> m = 'hi'
    => "hi"
    [4] pry(main)> m.extend(Chainable).as { |m| m << '!' }.as { |m| m+'?'}
    => "hi!?"
    [5] pry(main)> m
    => "hi"
    

    If anybody sees anything wrong with this code, please let me know! Hope this helps.

提交回复
热议问题