Friday, January 21, 2011

Abusing Ruby Operators

I've been looking at different ways to "pipe" objects, where the previous pipe object becomes the scope of the next.  The allows you perform multiple operations on an object, then pass it on to the next pipe operation.  For example (not a real language):
"Foo,Bar".split "," | first.upcase + last.downcase | reverse
The closest I could get in Ruby is this:
"Foo,Bar".split(",") --> { first.upcase + last.downcase } --> { reverse }
and the code to make this happen:
module Pipe
  def -( expr )
    alias :minus :-
  
    if expr.instance_of? Proc
      self.instance_eval( &expr )
    else
      minus( expr )
    end
  end
end

class String
  include Pipe
end

class Array
  include Pipe
end
I would never abuse the minus operator so badly though. Or would I :)