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
Defining a method that accepts any number of parameters and just discards them all
The above
hello
method only needs toputs
"hello"
on the screen and callsuper
- but since the superclasshello
defines parameters it has to as well - however since it doesn't actually need to use the parameters itself - it doesn't have to give them a name.Another fun addition in 1.9 Proc functionality is Proc#curry which allows you to turn a Proc accepting n arguments into one accepting n-1. Here it is combined with the Proc#=== tip I mentioned above:
Short inject, like such:
Sum of range:
use anything that responds to
===(obj)
for case comparisons:Module
(and thusClass
),Regexp
,Date
, and many other classes define an instance method :===(other), and can all be used.Thanks to Farrel for the reminder of
Proc#call
being aliased asProc#===
in Ruby 1.9.module_function
Module methods that are declared as module_function will create copies of themselves as private instance methods in the class that includes the Module:
If you use module_function without any arguments, then any module methods that comes after the module_function statement will automatically become module_functions themselves.
Don't know how hidden this is, but I've found it useful when needing to make a Hash out of a one-dimensional array: