Superators
Jay Phillips has just released a terribly snazzy new Ruby package, called “Superators.” Check out his post if you want the full scoop, but the gist of it is that you can define certain operators that aren’t explicitly built into the language.
Some of the examples he gives are <---, -~+~-, and ++.
A commenter suggested =|===- as a “ninja sword” operator.
The general rule is that you can take any pre-existing infix operator
and append +, -, or ~ to it any number of times.
The most amazing thing about this is that it’s done in pure Ruby. There’s no parser redefinition or syntax-tree crawling. Just some terribly clever hacks.
The trick is that Ruby doesn’t care about whitespace for prefix operators.
-2 and - 2 and - 2 all end up as -2.
In addition, "foo" << ~"bar" and "foo" <<~ "bar" are equivalent.
Using this, Jay was able to overridden the unary operators for Object and make them figure out in what pattern they were called. When defining a superator, the relevant binary operator was also overridden and made to dispatch the proper superator.
Unfortunately, there are issues.
For example, if the last operator in a superator
(e.g. - in -~+~-)
is defined for the operand
(e.g. in 12 -~+~- 42, - is defined for 42)
the superator won’t work.
It’ll apply the last operator to the operand
rather than doing any superator-y manipulation.
This makes dealing with Fixnums pretty much out of the question, which means Superators would be pretty impractical to actually work with. Nevertheless, it’s a very cool idea, and a very clever hack. Kudos to Jay.
About Me
No More RSS


