« Deploying Rails Applications | Main | Art in Programming »

August 30, 2007

Superators: neat Ruby hack

Superators
Image stolen from jicksta.com


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.

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/t/trackback/2226312/21229269

Listed below are links to weblogs that reference Superators: neat Ruby hack:

Comments

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.

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

Clever, but I also prefer

'Clarity Over Cleverness'.

Post a comment

If you have a TypeKey or TypePad account, please Sign In

Now in Beta

  • Programming Ruby, 3rd Edition
    Third Edition, Covering Ruby 1.9, now in beta
My Photo

Pragmatic Stuff

Photos

  • www.flickr.com
    This is a Flickr badge showing public photos from pragdave tagged with pragdave_badge. Make your own badge here.

Site Search

  • Google Search

    The web
    PragDave