Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.
Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.
See also:
- Hidden features of C#
- Hidden features of Java
- Hidden features of JavaScript
- Hidden features of Ruby on Rails
- Hidden features of Python
(Please, just one hidden feature per answer.)
Thank you
Peter Cooper has a good list of Ruby tricks. Perhaps my favorite of his is allowing both single items and collections to be enumerated. (That is, treat a non-collection object as a collection containing just that object.) It looks like this:
Destructuring an Array
Where:
Using this technique we can use simple assignment to get the exact values we want out of nested array of any depth.
The "ruby" binary (at least MRI's) supports a lot of the switches that made perl one-liners quite popular.
Significant ones:
put
s at the end of each loop iterationSome examples:
Feel free to google "ruby one-liners" and "perl one-liners" for tons more usable and practical examples. It essentially allows you to use ruby as a fairly powerful replacement to awk and sed.
Fool some class or module telling it has required something that it really hasn't required:
This is useful for example when requiring A that in turns requires B but we don't need B in our code (and A won't use it either through our code):
For example, Backgroundrb's
bdrb_test_helper requires
'test/spec'
, but you don't use it at all, so in your code:One final one - in ruby you can use any character you want to delimit strings. Take the following code:
If you don't want to escape the double-quotes within the string, you can simply use a different delimiter:
As well as avoiding having to escape delimiters, you can use these delimiters for nicer multiline strings:
Warning: this item was voted #1 Most Horrendous Hack of 2008, so use with care. Actually, avoid it like the plague, but it is most certainly Hidden Ruby.
Superators Add New Operators to Ruby
Ever want a super-secret handshake operator for some unique operation in your code? Like playing code golf? Try operators like -~+~- or <--- That last one is used in the examples for reversing the order of an item.
I have nothing to do with the Superators Project beyond admiring it.