Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

methods

ruby

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

like image 922
oFca Avatar asked Apr 04 '12 20:04

oFca


People also ask

What do square brackets mean in Ruby?

Square brackets indicate character classes in Ruby regular expressions.

How do you define a method in Ruby?

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.

What happens when you call a method in Ruby?

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 .

How do you call a method in Ruby?

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.


Video Answer


1 Answers

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) 
like image 133
Jörg W Mittag Avatar answered Sep 18 '22 02:09

Jörg W Mittag