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"] = 3
ary = []
/[^A-Fa-f0-9]/
"Is a string"[5,3]
Square brackets indicate character classes in Ruby regular expressions.
Square Brackets are placed around extra information in a text; and are typically used for editorial comments, corrections, and clarifications. Square brackets can also be used to add something into a sentence that was taken out by the writer.
You can't use curly braces, but indentation doesn't matter either. Instead of a closing brace, Ruby uses the end keyword. I'd still recommend indenting carefully, though — poorly indented code will trick human readers even if braces are used correctly.
There are two ways of defining a block in Ruby: The first is using the do.. end keyword, the other is using a pair of curly braces. Do.. end block is mainly used when defining a block of code that spans multiple lines, while curly braces {} are used when defining a block of code that spans a single line.
The square brackets are in two strict contexts and one optional one:
Defining Arrays
Arrays, i.e. a data structure providing and ordered list of elements can be specified in code by using a syntax like [1,2,3]
. This creates an array with the three elements 1
, 2
, and 3
in exactly that order. you can then iterate over the array using on of the iterator functions like each
or map
or you can directly access a specific elements by its index id as shown below.
Accessing Elements in Arrays and Hashes
Hashes (also called hashmaps, dictionaries, or associative arrays in other languages) also contain elements similar to arrays. The are different from this in the way that they store their data unordered. Data is not accessed by an integer id as is the case by arrays but with an arbitrary key (commonly a symbol or a string). This is different from e.g. PHP where the same Array type is used for both.
This access to the data is facilitated by methods called []
and []=
for both 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 the common use case for the brackets. In Ruby code, you might sometimes see other classes implementing the bracket functions. They do so to allow an access similar to either arrays or hashes and it is then generally expected that these classes behave similar to those but this is in no way enforced. See also Duck Typing.
% Notation
Ruby has a third syntax to create strings (and other objects) apart from the common. Using this syntax, the literal string in code are not enclosed by "
or '
but use a special delimiter. It starts with a percent sign, a single character specifying the object to be created and almost any character to chose as a delimiter:
a = %w[foo bar baz]
b = %w{foo bar baz}
c = %wxfoo bar bazx
d = ["foo", "bar", "baz"]
All three example create the same array. Please see the some documentation on how to use this syntax and which other modifier characters are available in Ruby.
While it is common to use brackets here, it is on no way required and can be substituted if required. It is just advisory here as the most common usage of this notation is to create an array of elements from a whitespace-seperated string (as seen above). As such, the usage of brackets makes it further clear that an array is returned as the syntax looks similar to the basic array specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With