Well, only for my own notes I left and took a closer look at it and, relying on Holger Just answer , think of the following: the use of square brackets in Ruby can be divided into 6 uses, 3 of them are part of the Ruby method definitions and 3 of them are semantic constructions.
Method Definition
Creating an object using the methods of the class Array :: [], Hash :: []
Array.[](1,2,3) #=> [1,2,3] #Un-sugared notation Array["a","b","c"] #=> ["a","b","c"] #Sugared equivalent Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
Nothing to do with literals, although he does the same.
Link to an element through instance methods Array # [], Bignum # [], Continuation # [], Fixnum # [], Hash # [], MatchData # [], Method # [], Pro # [], String # [] , Struct # [], Symbol # [], Thread # [] and methods of the class Dir :: [], ENV :: []
ary = [1,2,"abc", [15,16,[26,27]]] ary.[](2) #=> "abc" #Un-sugared notation ary[2] #=> "abc" #Sugared equivalent ary[0,2] #=> [1,2] ary[3][2][1] #=> 26 [1,2,3][0] #=> 1 "Is a string"[7,3] #=> "rin"
Assigning an Element Using Instance Methods Array # [] =, Hash # [] =, String # [] =, Struct # [] =, Thread # [] = and the class method ENV :: [] =
ary = [1,2,3] ary.[]=(1,"abc") #=> [1,"abc",3] #un-sugared notation ary[2] = "def" #=> [1,"abc","def"] #Sugared equivalent hash = {"a"=>1, "b"=>2} hash["a"] = 3 #=> {"a"=>3, "b"=>2}
Semantic constructions
Creating an Object Using the Literal Designer
ary = []
Ruby has a bunch of constructor literals that create an object of the corresponding class using (usually) a simple pair of characters, and square brackets are a constructor literal for array objects: Array [] , Hash {} , Proc ->(){} , Range .. and ... , Regexp // , String "" and '' , Symbol : and :"" .
Creating an object using% notation
%q[hello there you] #=> "hello there you" # String % notation %w[hello there you] #=> ["hello", "there", "you"] # Array % notation
Strictly speaking, this is a square notation, but rather a designation of two characters, of which you can use square brackets if you want. Thus, %q@hello there you@ equivalent.
Ruby regular expressions
/[^A-Fa-f0-9]/
Square brackets indicate character classes in Ruby regular expressions.
I found another use of [] as a template for use in the Dir :: glob method, but it should act exactly the same as in regular expressions. However, this indicates that more features are possible in Ruby 1500+.