Define an each iterator, etc

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,

···

2007/2/26, Guillaume Nargeot <guillaume.nargeotDONOTFUCKINGSPAM@fusionsystems.co.jp>:

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 Mettraux -///- http://jmettraux.openwfe.org

Hi --

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

···

On 2/25/07, Guillaume Nargeot <guillaume.nargeotDONOTSPAM@fusionsystems.co.jp> wrote:

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black\)
   (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf\)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)