So the loose tolerance of Ruby to use braces sometimes and not REQUIRE them has led to alot of confusion for me as I'm trying to learn Rails and when/where to use each and why?
Sometimes parameters or values are passed as (@user, @comment)
and other times they seem to be [ :user => comment ]
and still others it's just: :action => 'edit'
I'm talking about the us of [ ] vs ( ) vs { }
What ARE the rules? And are there any tricks you have to help you remember?
Parentheses ()
are for grouping logical or mathematical expressions and grouping arguments to a function call, e.g.:
a = 2 * (3 + 4)
b = (x==y) || (m==n)
Hash.new.send('[]=', :a, :b)
Curly Braces {}
are used for hash literals and blocks, e.g.:
h = {1=>2, 2=>3}
h.each {|k,v| puts k+v}
Square Brackets []
are used for array literals, array indexing and slicing, and fetching from a hash, e.g.:
arr = [1, 2, 3]
two = arr[1]
three = h[2]
To confuse the matter, hash literals can also be used in-place as an argument to a method call without needing the curly braces or parentheses as long as it is the last argument (thanks samuil). Additionally, hash literals can be used in-place in square brackets to create a single-item array containing the hash:
puts 1=>2, 3=>4 #=> 1234
[5=>6, 7=>8] #=> [{5=>6, 7=>8}]
When in doubt, always use parentheses to group items and wrap your hashes in curly braces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With