Friday, October 21, 2016

Elixer style pipes in ruby.

Pipes that are like mappings can already be reproduced in Ruby using the map method. Elixer allows you to treat the item as the first argument of a function call. This is an experiment with inserting arguments into procs.
 
class Proc
  def <<(*args)
    -> (*items) { self.call(*items, *args) }
  end
end

adder = -> (*args) { args.inject(&:+) }

puts [1,2,3,4,5]
  .map(&adder << 1)
  .map(&adder.<<(10, 100)).inspect 
 
A more Elixer style chain with class methods by monkey patching the Method class.
 
class Method
  def <<(*args)
    -> (*items) { self.call(*items, *args) }
  end
end

class Mathx
  def self.product(*args)
    args.inject(&:*)
  end

  def self.division(*args)
    args.inject(&:/)
  end
end

puts [1,2,3,4,5]
  .map(&Mathx.method(:product) << 4)
  .map(&Mathx.method(:division) << 2).inspect