Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby custom iterators
    text
    copied!<p>I have a class <code>game</code> which contains some arrays of custom objects (dinosaurs, cacemen etc.), that are returned by different accessors, such as <code>game.dinosaurs</code>, <code>game.cavemen</code> etc.</p> <p>At present, all these accessors just return the internally stored arrays. But now I'd like to add some custom iteration methods to these arrays returned by those accessors, to be able to write code such as <code>game.dinosaurs.each_carnivore { ... }</code> etc. similarly to <code>each_element</code> and <code>each_attr</code> iterators in <code>LibXML::XML::Node</code>. But the objects returned from my accessors <code>game.dinosaurs</code> and <code>game.cavemen</code> have to behave like arrays still.</p> <p>How are things like that usually done in Ruby? Should I make the objects returned from my accessors to be some custom classes derived from Ruby's <code>Array</code> class? Or maybe should I just create a custom class with <code>Enumerable</code> mixed in?</p> <p>I know I can use <code>map</code> or <code>select</code> externally on my collections, but I wanted to encapsulate these iterations internally that my class's users won't need to bother how to set up an iteration to select only carnivore dinosaurs from the internal array.</p> <p><strong>Edit:</strong> I'm not asking about how to use iterators or how to implement them, but how to add just some custom iterators to object which previously were just plain arrays (and still need to be).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload