Forum: Ruby define an each iterator, etc.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Guillaume Nargeot (Guest)
on 2007-02-26 03:45
(Received via mailing list)
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
John M. (Guest)
on 2007-02-26 03:50
(Received via mailing list)
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,
David A. Black (Guest)
on 2007-02-26 03:52
(Received via mailing list)
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 :-)

  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
This topic is locked and can not be replied to.