How does this work? def[](own_arg_1, own_arg_2)

K

Krekna Mektek

Hi,

While reading some code, which tells that one can define a new
indexing operator, some of my neurons triggered a question. When
evaluating this code:

class Song
def[](from_time, to_time)
result =3D Song.new(self.title + " [extract]",
self.artist
to_time - from_time)
result.set_start_time(from_time)
result
end
end

song[0,15].play

I was thinking: when one usually defines a method, the arguments are
placed after the method name, which is '[]' here, or so I thought.
That would be song[](0,15).play

How come it works 'just' by putting the argument between the brackets?

Krekna Mektek
 
D

David A. Black

Hi --

Hi,

While reading some code, which tells that one can define a new
indexing operator, some of my neurons triggered a question. When
evaluating this code:

class Song
def[](from_time, to_time)
result = Song.new(self.title + " [extract]",
self.artist
to_time - from_time)
result.set_start_time(from_time)
result
end
end

song[0,15].play

I was thinking: when one usually defines a method, the arguments are
placed after the method name, which is '[]' here, or so I thought.
That would be song[](0,15).play

Actually the full method-call version would be:

song.[](0,15).play # note the first dot
How come it works 'just' by putting the argument between the brackets?

Because Matz is nice and gave us some nice syntactic sugar :)


David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,968
Members
47,524
Latest member
ecomwebdesign

Latest Threads

Top