Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The answer is but a click away: the documentation for <a href="http://www.ruby-doc.org/core-1.9.3/Enumerator.html" rel="nofollow">Enumerator</a>:</p> <blockquote> <p>Most [<code>Enumerator</code>] methods [but presumably also <code>Kernel#to_enum</code> and <code>Kernel#enum_for</code>] have two forms: a block form where the contents are evaluated for each item in the enumeration, and a non-block form which returns a new <code>Enumerator</code> wrapping the iteration.</p> </blockquote> <p>It is the second that applies here:</p> <pre><code>enum = [4, 1, 2, 0].to_enum(:count) # =&gt; #&lt;Enumerator: [4, 1, 2, 0]:count&gt; enum.class # =&gt; Enumerator enum_ewi = enum.each_with_index # =&gt; #&lt;Enumerator: #&lt;Enumerator: [4, 1, 2, 0]:count&gt;:each_with_index&gt; enum_ewi.class # =&gt; Enumerator enum_ewi.each {|elem, index| elem == index} # =&gt; 2 </code></pre> <p>Note in particular irb's return from the third line. It goes on say, "This allows you to chain Enumerators together." and gives <code>map.with_index</code> as an example.</p> <p>Why stop here?</p> <pre><code> enum_ewi == enum_ewi.each.each.each # =&gt; true yet_another = enum_ewi.each_with_index # =&gt; #&lt;Enumerator: #&lt;Enumerator: #&lt;Enumerator: [4, 1, 2, 0]:count&gt;:each_with_index&gt;:each_with_index&gt; yet_another.each_with_index {|e,i| puts "e = #{e}, i = #{i}"} e = [4, 0], i = 0 e = [1, 1], i = 1 e = [2, 2], i = 2 e = [0, 3], i = 3 yet_another.each_with_index {|e,i| e.first.first == i} # =&gt; 2 </code></pre> <p>(Edit 1: replaced example from docs with one pertinent to the question. Edit 2: added "Why stop here?)</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