M
Mohnish Chaudhary
Hi,
I am a newbie and am following Programming Ruby 2nd edition. On page 44,
there's this piece of code,
class SongList
def initialize
@songs = Array.new
end
def [](index)
@songs[index]
end
end
Now, the following code works fine,
list = SongList.new
...
list[0] # this works fine, but how ?
...
What I don't understand is how is "list[0]" working ? The syntax of the
method specified is "[](index)", so how come can we pass the index
within the braces instead of after it i.e shouldn't it be "list.[](0)"?
But strangely, both work!
Please let me understand how "list[0]" works fine for the function
defined as "[](index)".
Regards,
Mohnish
=======
I am a newbie and am following Programming Ruby 2nd edition. On page 44,
there's this piece of code,
class SongList
def initialize
@songs = Array.new
end
def [](index)
@songs[index]
end
end
Now, the following code works fine,
list = SongList.new
...
list[0] # this works fine, but how ?
...
What I don't understand is how is "list[0]" working ? The syntax of the
method specified is "[](index)", so how come can we pass the index
within the braces instead of after it i.e shouldn't it be "list.[](0)"?
But strangely, both work!
Please let me understand how "list[0]" works fine for the function
defined as "[](index)".
Regards,
Mohnish
=======