Ruby Ruby 的 pipe

mizuhashi · 2016年12月08日 · 最后由 mizuhashi 回复于 2016年12月08日 · 2468 次阅读

(误

class Object
  class Proxy < BasicObject
    def method_missing name, *args, &block
      @target = @target.send(name, *args, &block)
    end

    def initialize target
      @target = target
    end
  end

  def pipe &block
    Proxy.new(self).instance_eval &block
  end
end

p [1,2,3].map{|x| %w{a b c d}[x] }.join.capitalize # => "Bcd"

[1,2,3].pipe do
  map{|x| %w{a b c d}[x] }
  join
  capitalize
  p self
end # => "Bcd"

再来一个

class DelayedMethod
  attr_reader :proc_chain

  def initialize proc
    @proc_chain = [proc]
  end

  def >> another
    @proc_chain.concat another.proc_chain
    self
  end
end

_ = Object.new
class << _
  def method_missing name, *args, &block
    DelayedMethod.new(->(x){ x.send(name, *args, &block ) })
  end

  def log
    DelayedMethod.new(->(x){ p x })
  end
end

class Object
  def >> delayed_method
    delayed_method.proc_chain.reduce(self){|acc, x| x.(acc)}
  end
end

[1,2,3] >> _.map{|x| %w{a b c d}[x] } >> _.join >> _.capitalize >> _.log # => "Bcd"

pipe 是单向的吗?

#2 楼 @tablecell 就是换了个写法的链式调用

mizuhashi Ruby 模仿:|> 提及了此话题。 08月12日 14:50
需要 登录 后方可回复, 如果你还没有账号请 注册新账号