Square Brackets
The square brackets ([]
) are used in two distinct ways. First, to create arrays of objects. Second, as an overrideable method that is often (but not always!) semantically an accessor method (plus the counterpart setter method []=
).
So, we might define an array and then access some of its values like so:
> food = [:taco, :burrito, :torta, :enchilada]
=> [:taco, :burrito, :torta, :enchilada]
> food[2]
=> :torta
> food[-1]
=> :enchilada
> food[0]
=> :taco
Any class can define a ::[]
class method, even a class that doesn't exactly behave like a collection. The ActiveRecord migration
class ↗ is a good example of this. When writing a Rails migration, we have to indicate the version compatibility of the migration.
class CreateBooks < ActiveRecord::Migration[7.2]
def change
create_table :books do |t|
t.string :title
t.date :publication_date
t.string :author
t.timestamps
end
end
end
Let's jump back to Array
and see both its class method ::[]
and instance method #[]
.
This Array::[]
class method ↗ allows us to define an array instance. These are two different ways of calling the same method.
> Array.[](1,2,3)
=> [1, 2, 3]
> Array[1,2,3]
=> [1, 2, 3]
Once we have an instance, then we can use the Array#[]
instance method to access values from the array. To illustrate the point that this is a method like any other method, we can call with a dot and arguments passed in via the parentheses.
> arr = Array.[](1,2,3)
=> [1, 2, 3]
> arr.[](1)
=> 2