9

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

hammar
  • 138,522
  • 17
  • 304
  • 385
Gunchars
  • 9,555
  • 3
  • 28
  • 27

4 Answers4

8

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
Jim Deville
  • 10,632
  • 1
  • 37
  • 47
2
a = Proc.new { |x| x + 1 }
b = Proc.new { |x| x * 10 }
c = Proc.new { |x| b.call(a.call(x)) }
Arman H
  • 5,488
  • 10
  • 51
  • 76
  • Please explain what sugar is missing from this answer? – Arman H May 28 '13 at 19:28
  • Sorry if I wasn't clear: you're given `a` and `b`. You need to get `c`. You can of course write a new proc, but I'm wondering if there's a shorter way, like `b.wrap a` or something. – Gunchars May 28 '13 at 19:28
2

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}
Rune FS
  • 21,497
  • 7
  • 62
  • 96
1

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
EJAg
  • 3,210
  • 2
  • 14
  • 22