title: How does defining [square bracket] method in Ruby work?
body: <p>I am going through <a href="http://www.ruby-doc.org/docs/ProgrammingRuby/">Programming Ruby - a pragmatic programmers guide</a> and have stumbled on this piece of code:</p>
  
  <pre><code>class SongList
    def [](key)
      if key.kind_of?(Integer)
        return @songs[key]
      else
        for i in 0...@songs.length
          return @songs[i] if key == @songs[i].name
        end
      end
      return nil
    end
  end
  </code></pre>
  
  <p>I do not understand how defining [ ] method works? </p>
  
  <p>Why is the key outside the [ ], but when the method is called, it is inside [ ]? </p>
  
  <p>Can key be without parenthesis? </p>
  
  <p>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</p>