On Tue, 6 Nov 2007, Fernando C. wrote:
I often see hashes used as a form of named parameters, with some variations.
However, I couldn’t find the idiom properly explained anywhere.
I’m just missing it? Where is it?
Would anyone like to explain the idiom here? specially, when, why and how it
You pass a hash to the method, using pre-determined keys that serve as
pseudo-keywords. For example:
enroll(:applicant => person, :date => Time.now, :status => “admin”)
(Notice that I don’t have to wrap the hash in curly braces. The rule is
that if a hash is the last thing in the argument list, you can drop
The “why” part of it is that it gives the caller a way to (a) document
what the arguments are for a little bit, and (b) not worry about the
order of arguments, since hash keys can appear in any order.
It worries me that while it adds clarity at the point of call, it takes it
away at the function defintion point, so I haven’t dare to use it yet.
It’s a bit wordier than plain local variable names, but usually worth
the trade-off if you think it’s important to make things a little
easier for the caller.
Note that in 1.9, my example could be written as:
enroll(applicant: person, date: Time.now, status: “admin”)