The answer to your wonderment isn’t particular to Rails but is a
function of Ruby’s flexibility in passing in arguments to a method.
The link_to method has four formal arguments, the first of which is
required. The second and third both have default values (which they
assume in absence of the prescence of a second and third argument,
respectively) and the fourth represents a multi-valued argument where
any amount of arguments greater than the first three are collected
into an array and passed as the last argument.
As for the answer to your question, I bet there is a best practice
because Rails is typically opinionated software. My guess would be
that it is the first way which is best practice because it is a common
Rails idiom and, IMO, more sincere to the intent of the arguments.
Obviously, the second way works but looking at the source code, I’m
not exactly sure why it works. I’m going to have to step through with
a debugger so let me say thanks for the interesting question.
After stepping through the debugger, I see that in your second
example, the second two arguments (:controller => “foo”, :action =>
“bar”) are considered part of one hash and are passed to url_for as
the first argument(in this file
- NOTE: the link didn’t display source code for me but at least points
you in the correct file for the source code, your local install
location of the source code may vary).
Maybe someone with better understanding of ruby than I can explain why
the second two arguments are considered part of one hash as opposed to
two one element hashes? (I would assume its something to do with the
of ‘=>’ and its subsequent effects? I wouldn’t think a symbol is the
trigger. Or is it that both strings and symbol objects have an
operator (method) ‘=>’ which takes in an argument/expression and
returns a hash
object? How would I verify my supposition? Is there a ruby compiler
with ruby source code? Or do I go try to grok C code?)]