.[ ] Method…Huh?

I came across the blog post “What I Wish a Ruby Programmer Had Told Me One Year Ago” and started reading through the author Simon’s code for the first iteration of his todo app to figure out what was going on. One method he used was:

1
2
3
def [](id)
  @list[id]
end

This had me pretty confused at first. Then when I looked at how he was running the code I saw he was calling this method like you would access an element in an array.

1
2
list = TodoList.load("todo.td")
list[0].done = true

It turns out in Ruby you can use special characters to name methods including the array lookup syntax, square brackets. In this way he names the method [ ] and passes it an (id), which is then passed to the array @list to lookup that element in the @list array. Essentially he’s creating a lookup on the instance of his class TodoList, so he can use [ ] to lookup specific todo items just like he would if here were accessing them in array, which technically he is…the @list array. Pretty Cool!

Check out this Stackoverflow answer for some good examples of how to use the [ ] method, http://stackoverflow.com/questions/10018900/how-does-defining-square-bracket-method-in-ruby-work

Here is another great Stackoverflow answer about Ruby Method names, http://stackoverflow.com/questions/10542354/what-are-the-restrictions-for-method-names-in-ruby

Copyright © 2015 - Kyle Doherty. Powered by Octopress