Writing Ruby Square Bracket Methods
March 26 2015
One thing that many early Rubyists fail to realize about square brackets (
) in Ruby is that they are nothing more than a method with some added syntactic sugar. Everything is an object in Ruby, and square brackets are just a method call on those objects.
The language has given
 a special syntax, but everything is an object at the end of the day.
Take a look at this example:
It also works for setting array elements with a similar method,
Taking this realization one step further you will realize that a class doesn’t need to be an Array or Hash descendant to take advantage of the square bracket syntax.
Let’s build a simple object to illustrate the possibilities:
The syntax for defining these methods may be surprising, but it can be a great way to encapsulate logic with a familiar interface. The next time you find yourself needing to express collection lookups on your objects, consider using square brackets.