How to combine two procs into one?

╄→尐↘猪︶ㄣ 提交于 2019-12-21 10:52:21

问题


Just wondering if there's a syntax shortcut for taking two procs and joining them so that output of one is passed to the other, equivalent to:

a = ->(x) { x + 1 }
b = ->(x) { x * 10 }
c = ->(x) { b.( a.( x ) ) }

This would come in handy when working with things like method(:abc).to_proc and :xyz.to_proc


回答1:


More sugar, not really recommended in production code

class Proc
  def *(other)
    ->(*args) { self[*other[*args]] }
  end
end

a = ->(x){x+1}
b = ->(x){x*10}
c = b*a
c.call(1) #=> 20



回答2:


a = Proc.new { |x| x + 1 }
b = Proc.new { |x| x * 10 }
c = Proc.new { |x| b.call(a.call(x)) }



回答3:


you could create a union operation like so

class Proc
   def union p
      proc {p.call(self.call)}
   end
end
def bind v
   proc { v}
end

then you can use it like this

 a = -> (x) { x + 1 }
 b = -> (x) { x * 10 }
 c = -> (x) {bind(x).union(a).union(b).call}



回答4:


An updated answer. Proc composition is already available in Ruby 2.6. There are two methods << and >>, differing in the order of the composition. So now you can do

##ruby2.6
a = ->(x) { x + 1 }
b = ->(x) { x * 10 }
c = a >> b
c.call(1) #=> 20


来源:https://stackoverflow.com/questions/16799788/how-to-combine-two-procs-into-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!