Your browser may have trouble rendering this page. See supported browsers for more information.

|<<>>|168 of 273 Show listMobile Mode

The Ruby language: where you can randomize your base class

Published by marco on

 I have never really examined Ruby in detail but it seems to be even more of a treasure-trove of ad-hoc features than PHP.

It takes full advantage of being evaluated at run-time to offer features that I haven’t seen in even other dynamic languages. Some of these features seem like they might be nice shortcuts but also seem like they would be difficult to optimize. Not only that, but they seem so obscure that they would likely will trip up even more seasoned users of the language.

At any rate, the one I found to be most brash was methods in class definitions by bjeanes (StackOverflow). (The article is a treasure trove of other gems, no pun intended.)

The example below shows how that might work.

class RandomSubclass < [Array, Hash, String, Fixnum, Float, TrueClass].sample

end

RandomSubclass.superclass # could output one of 6 different classes.

The language allows you to call methods from the “extends” clause. The example above creates an array of class names, then calls the sample method on them to yield a base class. The actual base class is not only unknown at compile time, it is also unpredictable at runtime.

The example above is contrived and makes the feature seem like it’s only for the reckless. It’s clear that serious software would have to forbid or strictly limit the use of such a feature, but I can see where it would be useful.

For example, you may want to change your base class depending on deployment parameters. If you’re deploying to a testing or staging environment, you’ll use a base class that includes more logging, profiling and debugging code. For production, you switch to a base class that’s optimized. If the class interface remains the same, then using this feature wouldn’t be as dangerous as it initially appeared.

Still, ensuring quality and enforcing architecture in software written in such a language would require a strict development process and discipline and vigilance from all involved.