How does defining [square bracket] method in Ruby work?

methods, ruby

Solution

Methods in ruby, unlike many languages can contain some special characters. One of which is the array lookup syntax.

If you were to implement your own hash class where when retrieving an item in your hash, you wanted to reverse it, you could do the following:

class SillyHash < Hash

  def [](key)
    super.reverse
  end

end

You can prove this by calling a hash with the following:

a = {:foo => "bar"}
 => {:foo=>"bar"} 
a.[](:foo)
 => "bar" 
a.send(:[], :foo)
 => "bar" 

So the def [] defined the method that is used when you do `my_array["key"]` Other methods that may look strange to you are:

class SillyHash < Hash

  def [](key)
    super.reverse
  end

  def []=(key, value)
    #do something
  end

  def some_value=(value)
    #do something
  end

  def is_valid?(value)
    #some boolean expression
  end

end

Just to clarify, the definition of a `[]` method is unrelated to arrays or hashes. Take the following (contrived) example:

class B
  def []
    "foo"
  end
end

 B.new[]
 => "foo" 

Problem

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] else for i in 0...@songs.length return @songs[i] if key == @songs[i].name end end return nil end end ``` 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

Original source