There’s something about Ruby
What continually excites and amazes me about Ruby is how expressive it is, how extensible it is, and how elegant it is.
Because you can extend any class/object in Ruby, and because everything is an object, you can essentially refine or redefine the language and its idioms to suit your thinking or preferred way of expression.
Case in point – if you deal with collections, ranges or subclasses you will have used one of the the following expressions (Ruby in Java-esque style):
x >= 0 && x < n obj.kind_of? SubClassA || obj.kind_of? ClassB some_range.include? -1 some_hash.keys.include? "ABC" symbol_array.include? :a_symbol
Here are the same expressions using a more Ruby-like idiom:
(0...n).include? x [SubClassA, SubClassB].include? obj.class some_range.include? -1 some_hash.include? "ABC" # Hash.include? is an alias for has_key? symbol_array.include? :a_symbol
Certainly more succinct than the first set of expressions, but are they really more expressive?
In particular, the [SubClassA, SubClassB].include? obj.class to me just sounds, well…funny.
All of the above more or less translates to “does set S include element E?“. Maybe it’s just me, but in my mind it’s just more intuitive to rephrase that question as “is E part of S?”
What I want is to be able to call some method on any object asking it whether it’s part of some collection or range.
Fortunately, it’s a cinch to ‘hack’ this into Ruby so I can use it any time I need or feel like it, and that’s what I’m about to do.