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
Class.new()
Create a new class at run time. The argument can be a class to derive from, and the block is the class body. You might also want to look at
const_set/const_get/const_defined?
to get your new class properly registered, so thatinspect
prints out a name instead of a number.Not something you need every day, but quite handy when you do.
Auto-vivifying hashes in Ruby
This can just be damn handy.
Hashes with default values! An array in this case.
Very useful in metaprogramming.
Boolean operators on non boolean values.
&&
and||
Both return the value of the last expression evaluated.
Which is why the
||=
will update the variable with the value returned expression on the right side if the variable is undefined. This is not explicitly documented, but common knowledge.However the
&&=
isn't quite so widely known about.is equivalent to
It's very handy for destructive operations that should not proceed if the variable is undefined.
The Symbol#to_proc function that Rails provides is really cool.
Instead of
You can write:
Another tiny feature - convert a
Fixnum
into any base up to 36:And as Huw Walters has commented, converting the other way is just as simple: