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 [email protected] 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
Square brackets indicate character classes in Ruby regular expressions.
Defining & Calling the method: In Ruby, the method defines with the help of def keyword followed by method_name and end with end keyword. A method must be defined before calling and the name of the method should be in lowercase. Methods are simply called by its name.
In ruby, the concept of object orientation takes its roots from Smalltalk. Basically, when you call a method, you are sending that object a message. So, it makes sense that when you want to dynamically call a method on an object, the method you call is send .
We call (or invoke) the method by typing its name and passing in arguments. You'll notice that there's a (words) after say in the method definition. This is what's called a parameter. Parameters are used when you have data outside of a method definition's scope, but you need access to it within the method definition.
It's just syntactic sugar. There are certain syntax patterns that get translated into message sends. In particular
a + b
is the same as
a.+(b)
and the same applies to ==
, !=
, <
, >
, <=
, >=
, <=>
, ===
, &
, |
, *
, /
, -
, %
, **
, >>
, <<
, !==
, =~
and !~
as well.
Also,
!a
is the same as
a.!
and the same applies to ~
.
Then,
+a
is the same as
a.+@
and the same applies to -
.
Plus,
a.(b)
is the same as
a.call(b)
There is also special syntax for setters:
a.foo = b
is the same as
a.foo=(b)
And last but not least, there is special syntax for indexing:
a[b]
is the same as
a.[](b)
and
a[b] = c
is the same as
a.[]=(b, c)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With