I’m coming across the square bracket [] syntax quite a bit in Ruby, but it never seems to be doing the same thing. Can anyone list all the different uses for the square brackets [] in Ruby so my mind can get a handle on this seemingly endlessly versatile little symbol? (How is it possible that one symbol can do so much without the Ruby interpreter getting confused?)
Examples:
[]and[]=methods%q[...][1,2,3][0]hash["a"] = 3ary = []/[^A-Fa-f0-9]/"Is a string"[5,3]
Okay, just for my own notes I have gone and had a closer look at this and, building on Holger Just’s answer, come up with the following: the use of square brackets in Ruby can be divided into 6 uses, 3 of them a part of Ruby’s method definitions and 3 of them semantic constructs.
Method definition
Object creation via class methods Array::[], Hash::[]
Nothing to do with literal constructors, although it does the same thing.
Element reference via instance methods Array#[], Bignum#[], Continuation#[], Fixnum#[], Hash#[], MatchData#[], Method#[], Proc#[], String#[], Struct#[], Symbol#[], Thread#[], and class methods Dir::[], ENV::[]
Element assignment via instance methods Array#[]=, Hash#[]=, String#[]=, Struct#[]=, Thread#[]=, and class method ENV::[]=
Semantic constructs
Object creation via the array literal constructor
There are a bunch of literal constructors in Ruby that create an object of the relevant class via the use of (usually) a simple symbol pair, square brackets being the literal constructor for array objects: Array
[], Hash{}, Proc->(){}, Range..and..., Regexp//, String""and'', Symbol:and:"".Object creation via the % notation
It is not, strictly speaking, square-bracket notation, but rather two-symbol-pair notation of which you can use square brackets if you wish. So
%q@hello there you@is equally valid.Ruby’s regular expressions
Square brackets indicate character classes in Ruby regular expressions.
I did find another use of the
[], as a pattern for use in the Dir::glob method, but its supposed to act exactly as it does in regular expressions. Still, it indicates that there are possibly more uses hidden away in Ruby’s 1500+ methods.