views:

147

answers:

2

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?

+9  A: 

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. 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.

maerics
Note, that curly braces can be omitted when passing a hash to a function as an argument only if it is last one.
samuil
A: 

confusing !!!!!!!

werty