Braces: [Brackets], (Parentheses) & {Curlies} in Ruby & Rails
Asked Answered
H

1

9

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?

Hagood answered 23/7, 2010 at 23:45 Comment(1)
FYI, "{" and "}" are the only "Braces." The common term for all of those is brackets. When not specified the word "brackets" refers to square brackets.Manno
L
23

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.

Logwood answered 23/7, 2010 at 23:55 Comment(1)
Note, that curly braces can be omitted when passing a hash to a function as an argument only if it is last one.Corrode

© 2022 - 2024 — McMap. All rights reserved.