Superators: neat Ruby hack
So, I'm not sure if Jay Phillips (of Adhearsion fame) is trying to annoy the purists with a remarkably Perlish hack in Ruby. I just know that his superators gem is a clever bit of pure Ruby code that allows you to apparently define new infix operators in Ruby programs. Imagine the joy of being able to write
a /~ b
and
rocket <=- fuel
You can with superators:
require 'rubygems' require 'superators'class String
superator "<=-" do |arg|
self << arg.upcase
end
end
Is this a good idea? I don't know. I can see that it would have been useful in some DSLs that I've written. But I do think that it's a wonderfully clever implementation (it doesn't do anything nasty to the interpreter–it simply intercepts built-in operators (such as <<= and -) in my example above. And that's what makes it great. Every now and then, just when you think you know Ruby. someone comes up with something—such as symbol.to_proc or superators—that makes you go "oh!."
Every long-lasting relationship needs the occasional surprise to keep it interesting and fun. This kind of hack is one of the reasons I love Ruby.




To me, that sounds like a way to reduce the readability of your code... anyone viewing that bit of code is going to think "WTF does that do?" and have to go look up the "superator" definition to find out.
Sure, it's an neat trick, but not something I'd imagine being useful in quality code.
Posted by: David Precious | September 03, 2007 at 06:34 AM
Where this gets weird is that it's not just the type of object you are adding that gets extended; every object is extended in weird ways because of the unary operators that are being overloaded. That is, something like <=- involves not just overriding <= in String (fine enough) but also "-" in everything else, because you have to keep track of *anything* in the system that has been minused in case it gets less-than-or-equaled-to later.
A less intrusive trick in Python that would work in Ruby is |operator|, where "operator" is an object that just implements "|" appropriately: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122
Posted by: Ian Bicking | September 04, 2007 at 12:58 PM
Clever, but I also prefer
'Clarity Over Cleverness'.
Posted by: andy | October 10, 2007 at 09:53 AM