Define an each iterator, etc


#1

I would like to know if it’s possible to define iterators like each for
a
class you have written ?
Is it also possible to write methods that can have the following
behavior/usage:

object.method do |var|

something

end


#2

2007/2/26, Guillaume Nargeot
removed_email_address@domain.invalid:

I would like to know if it’s possible to define iterators like each for a
class you have written ?
Is it also possible to write methods that can have the following
behavior/usage:

object.method do |var|

something

end

Hi,

see http://www.rubycentral.com/book/tut_containers.html

look for “blocks and iterators”

Best regards,


#3

Hi –

On 2/25/07, Guillaume Nargeot
removed_email_address@domain.invalid wrote:

I would like to know if it’s possible to define iterators like each for a
class you have written ?

Sure. And if you define each and include Enumerator, you get all sorts
of methods along with it (find, select, inject, etc.).

Is it also possible to write methods that can have the following
behavior/usage:

object.method do |var|

something

end

Yes; such a method is called an iterator :slight_smile:

def object.m
yield 10
end

object.m do |var|
# var is equal to 10
end

Have a look in any Ruby tutorial book for more.

David