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
Wow, no one mentioned the flip flop operator:
create an array of consecutive numbers:
sets x to [0, 1, 2, 3, 4, 5]
From Ruby 1.9 Proc#=== is an alias to Proc#call, which means Proc objects can be used in case statements like so:
One of the cool things about ruby is that you can call methods and run code in places other languages would frown upon, such as in method or class definitions.
For instance, to create a class that has an unknown superclass until run time, i.e. is random, you could do the following:
This uses the 1.9
Array#sample
method (in 1.8.7-only, seeArray#choice
), and the example is pretty contrived but you can see the power here.Another cool example is the ability to put default parameter values that are non fixed (like other languages often demand):
Of course the problem with the first example is that it is evaluated at definition time, not call time. So, once a superclass has been chosen, it stays that superclass for the remainder of the program.
However, in the second example, each time you call
do_something_at
, theat
variable will be the time that the method was called (well, very very close to it)Fixnum#to_s(base)
can be really useful in some case. One such case is generating random (pseudo)unique tokens by converting random number to string using base of 36.Token of length 8:
Token of length 6:
I'm late to the party, but:
You can easily take two equal-length arrays and turn them into a hash with one array supplying the keys and the other the values:
(This works because Array#zip "zips" up the values from the two arrays:
And Hash[] can take just such an array. I've seen people do this as well:
Which yields the same result, but the splat and flatten are wholly unnecessary--perhaps they weren't in the past?)