Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It depends (as always). You could use an array subclass and you you could build a custom class and use composition and delegation. Here's a simple example with an array subclass:</p> <pre><code>class DinosaurArray &lt; Array def carnivores select { |dinosaur| dinosaur.type == :carnivore } end def herbivores select { |dinosaur| dinosaur.type == :herbivore } end def each_carnivore(&amp;block) carnivores.each(&amp;block) end def each_herbivore(&amp;block) herbivores.each(&amp;block) end end </code></pre> <p>And here's a simple one with composition and delegation:</p> <pre><code>class DinosaurArray def initialize @array = [] end def &lt;&lt;(dinosaur) @array &lt;&lt; dinosaur end def carnivores @array.select { |dinosaur| dinosaur.type == :carnivore } end def herbivores @array.select { |dinosaur| dinosaur.type == :herbivore } end def each(&amp;block) @array.each(&amp;block) end def each_carnivore(&amp;block) carnivores.each(&amp;block) end def each_herbivore(&amp;block) herbivores.each(&amp;block) end end </code></pre> <p>Both implementation can be used like this:</p> <pre><code>require 'ostruct' dinosaurs = DinosaurArray.new dinosaurs &lt;&lt; OpenStruct.new(type: :carnivore, name: "Tyrannosaurus") dinosaurs &lt;&lt; OpenStruct.new(type: :carnivore, name: "Allosaurus") dinosaurs &lt;&lt; OpenStruct.new(type: :herbivore, name: "Apatosaurus") puts "Dinosaurs:" dinosaurs.each.with_index(1) { |dinosaur, i| puts "#{i}. #{dinosaur.name}" } puts </code></pre> <p>But also has custom iterators:</p> <pre><code>puts "Carnivores:" dinosaurs.each_carnivore.with_index(1) { |dinosaur, i| puts "#{i}. #{dinosaur.name}" } puts puts "Herbivores:" dinosaurs.each_herbivore.with_index(1) { |dinosaur, i| puts "#{i}. #{dinosaur.name}" } </code></pre> <p>Output:</p> <pre><code>Dinosaurs: 1. Tyrannosaurus 2. Allosaurus 3. Apatosaurus Carnivores: 1. Tyrannosaurus 2. Allosaurus Herbivores: 1. Apatosaurus </code></pre>
 

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