How does defining [bracket] methods work in ruby?

I am going through Programming Ruby - a pragmatic programmers guide and have stumbled on this piece of code:

class SongList
  def [](key)
    if key.kind_of?(Integer)
      return @songs[key]
      for i in [email protected]
        return @songs[i] if key == @songs[i].name
    return nil

I do not understand how defining [ ] method works?

Why is the key outside the [ ], but when the method is called, it is inside [ ]?

Can key be without parenthesis?

I realize there are far better ways to write this, and know how to write my own method that works, but this [ ] method just baffles me... Any help is greatly appreciated, thanks

This question and all comments follow the "Attribution Required."

All Answers

Answers Loading...
Leave a Reply
You must be logged in to post a answer.
About the author