jrubyonrails - Braces: [Brackets], (Parentheses) & {Curlies} in Ruby & Rails -


so loose tolerance of ruby use braces sometimes , not require them has led alot of confusion me i'm trying learn rails , when/where use each , why?

sometimes parameters or values passed (@user, @comment) , other times seem [ :user => comment ] , still others it's just: :action => 'edit'

i'm talking of [ ] vs ( ) vs { }

what rules? , there tricks have remember?

parentheses () grouping logical or mathematical expressions , grouping arguments function call, e.g.:

a = 2 * (3 + 4) b = (x==y) || (m==n) hash.new.send('[]=', :a, :b) 

curly braces {} used hash literals , blocks, e.g.:

h = {1=>2, 2=>3} h.each {|k,v| puts k+v} 

square brackets [] used array literals, array indexing , slicing, , fetching hash, e.g.:

arr = [1, 2, 3] 2 = arr[1] 3 = h[2] 

to confuse matter, hash literals can used in-place argument method call without needing curly braces or parentheses long last argument (thanks samuil). additionally, hash literals can used in-place in square brackets create single-item array containing hash:

puts 1=>2, 3=>4 #=> 1234 [5=>6, 7=>8]    #=> [{5=>6, 7=>8}] 

when in doubt, use parentheses group items , wrap hashes in curly braces.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -