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
Use a Range object as an infinite lazy list:
More info here: http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/
Download Ruby 1.9 source, and issue
make golf
, then you can do things like this:Read the
golf_prelude.c
for more neat things hiding away.I find using the define_method command to dynamically generate methods to be quite interesting and not as well known. For example:
The above code uses the 'define_method' command to dynamically create the methods "press1" through "press9." Rather then typing all 10 methods which essentailly contain the same code, the define method command is used to generate these methods on the fly as needed.
A lot of the magic you see in Rubyland has to do with metaprogramming, which is simply writing code that writes code for you. Ruby's
attr_accessor
,attr_reader
, andattr_writer
are all simple metaprogramming, in that they create two methods in one line, following a standard pattern. Rails does a whole lot of metaprogramming with their relationship-management methods likehas_one
andbelongs_to
.But it's pretty simple to create your own metaprogramming tricks using
class_eval
to execute dynamically-written code.The following example allows a wrapper object to forwards certain methods along to an internal object:
The method
Wrapper.forwards
takes symbols for the names of methods and stores them in themethods
array. Then, for each of those given, we usedefine_method
to create a new method whose job it is to send the message along, including all arguments and blocks.A great resource for metaprogramming issues is Why the Lucky Stiff's "Seeing Metaprogramming Clearly".
One trick I like is to use the splat (
*
) expander on objects other than Arrays. Here's an example on a regular expression match:Other examples include:
The send() method is a general-purpose method that can be used on any Class or Object in Ruby. If not overridden, send() accepts a string and calls the name of the method whose string it is passed. For example, if the user clicks the “Clr” button, the ‘press_clear’ string will be sent to the send() method and the ‘press_clear’ method will be called. The send() method allows for a fun and dynamic way to call functions in Ruby.
I talk more about this feature in Blogging Shoes: The Simple-Calc Application