Tuesday, March 20, 2007

Hashes in Rails method calls

With a knowledge of hashes as well as symbols, you’re now in a position to understand
this construct:
<%= link_to "Click here",:controller => "work",:action => "show",:id => work.id %>
This is the classic Rails method-call look and feel.
This is a method call with two arguments: the string “Click here” and a three-key hash.

You might expect to see curly braces around the hash, like this:
link_to("Click here", { :controller => "work", :action => "show", :id => work.id })
But as a special sugar dispensation, Ruby permits you to end an argument list, when you call a method, with a literal hash without the curly braces.

Why does Ruby allow this special usage?
To facilitate and “prettify” precisely the kind of labeling of method arguments by descriptive name that’s so common in Rails.
Passing arguments as key/value pairs allows you to indicate what the arguments are for.
The elimination of the curly braces gives the idiom a clean look.

No comments: