What are all the different uses of square brackets in Ruby?

I come across the square bracket [] syntax quite a bit in Ruby, but it seems like it never does the same. Can anyone list all the different uses of square brackets [] in Ruby so that my mind can handle this seemingly infinitely versatile character? (How is it possible that one character can do so much if the Ruby interpreter is not confused?)

Examples:

  • [] and []= methods
  • %q[...]
  • [1,2,3][0]
  • hash["a"] = 3
  • ary = []
  • /[^A-Fa-f0-9]/
  • "Is a string"[5,3]
+8
syntax ruby
source share
2 answers

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+.

+7
source share

Square brackets are enclosed in two strict contexts and one optional:

Array Definition
Arrays, that is, the structure of the data representation and an ordered list of elements can be specified in the code using syntax like [1,2,3] . This creates an array with three elements 1 , 2 and 3 in exactly that order. you can iterate over the array using iterator functions like each or map , or you can directly access specific elements by index index, as shown below.

Access to elements in arrays and hashes
Hashes (also called hashmaps, dictionaries, or associative arrays in other languages) also contain elements similar to arrays. They differ from this in that they keep their data unordered. The data is not accessed by an integer id, as is the case with arrays, but with an arbitrary key (usually a character or a string). This is different from, for example, PHP, where the same array type is used for both.

This data access is facilitated using the [] and []= methods for hashes and arrays.

 my_array = [:a, :b, :c] second_element = my_array[1] # => :b # notice that the first element in arrays always has the index 0 my_hash = {:a => 1, :b => 2, :c => 3} element_of_b = my_hash[:b] # => 2 

This is a common use case for parentheses. In Ruby code, you can sometimes see other classes that implement bracket functions. They do this to allow access similar to arrays or hashes, and then it is usually expected that these classes behave similarly to those, but this does not apply in any way. See also Duck Typing .

% Designations
Ruby has a third syntax for creating strings (and other objects) besides common ones. Using this syntax, the literal line in the code is not enclosed in " or ' , but uses a special separator. It starts with a percent sign, a single character indicating the object to be created, and almost any character that will be selected as the separator:

 a = %w[foo bar baz] b = %w{foo bar baz} c = %wxfoo bar bazx d = ["foo", "bar", "baz"] 

All three examples create the same array. See the documentation on how to use this syntax and what other modifier characters are available in Ruby.

While parentheses are commonly used here, it is in no way required and can be replaced if required. Here's just a tip, since the most common use of this notation is to create an array of elements from a string separated by spaces (as shown above). Thus, using parentheses makes it even clearer that the array is returned, since the syntax is similar to the basic specification of the array.

+9
source share

All Articles