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
It's an operator overloader, it overrides or supplements the behavior of a method inside a class you have defined, or a class the behavior of which you are modifying. You can do it to other operators different from []. In this case you are modifying the behavior of [] when it is called on any instances of class SongList.
If you have songlist = SongList.new and then you do songlist["foobar"] then your custom def will come into operation and will assume that "foobar" is to be passed as the parameter (key) and it will do to "foobar" whatever the method says should be done to key.
Try
It's just syntactic sugar. There are certain syntax patterns that get translated into message sends. In particular
is the same as
and the same applies to
==
,!=
,<
,>
,<=
,>=
,<=>
,===
,&
,|
,*
,/
,-
,%
,**
,>>
,<<
,!==
,=~
and!~
as well.Also,
is the same as
and the same applies to
~
.Then,
is the same as
and the same applies to
-
.Plus,
is the same as
There is also special syntax for setters:
is the same as
And last but not least, there is special syntax for indexing:
is the same as
and
is the same as
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:
You can prove this by calling a hash with the following:
So the def [] defined the method that is used when you do
my_array["key"]
Other methods that may look strange to you are:Just to clarify, the definition of a
[]
method is unrelated to arrays or hashes. Take the following (contrived) example:the square brackets are the method name like
Array#size
you haveArray#[]
as a method and you can even use it like any other method:the last one is something like syntactic sugar and does exactly the same as the first one. The
Array#+
work similar:You can even add numbers like this:
the same works with
/
,*
,-
and many more.