I’m getting to grips with rails and whilst I feel I am progressing there is one thing that I am struggling to get to grips with and it’s very basic. I am trying to understand the different usage of [] {} and () Are there any good sources of their usage and are there any tips you can give to a beginner in recognizing when to use one or the other, or as I seem to see in some cases when they are not required at all?
I know this is extremely basic but I have struggled to find literature which explains concisely the interplay between them and Ruby or specifically RoR
I’m getting to grips with rails and whilst I feel I am progressing there
Share
It has nothing to do with RoR; the various brackets are Ruby language constructs.
[]is the array operator, for arrays and other classes that implement it (like a string taking a range to get substrings, or hashes to look up a key’s value):{}is for hashes, and one of two ways of delimiting blocks (the other beingbegin/end). (And used with#for string interpolation.)()is for method parameters, or for enforcing evaluation order in an expression.They’re sometimes optional if the statement has no ambiguity:
(They’re not always optional, and putting a space between the method call and its parenthetical parameter list can cause issues–best not to, IMO.)
(I probably missed something, too, but there’s the nutshell.)