Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Actually I think the following version is even more commonly seen:</p> <pre><code>def each @items.each { |i| yield i } end </code></pre> <p>This is equivalent to your first code sample. There is however a subtle difference between this and your second version:</p> <pre><code>class Test def initialize(items) @items = items end def each1 @items.each { |i| yield i } end def each2(&amp;block) @items.each(&amp;block) end end </code></pre> <p>Observe:</p> <pre><code>irb(main):053:0&gt; Test.new([1,2,3]).each2 =&gt; #&lt;Enumerator: [1, 2, 3]:each&gt; irb(main):054:0&gt; Test.new([1,2,3]).each1 LocalJumpError: no block given (yield) from (irb):43:in `block in each1' from (irb):43:in `each' from (irb):43:in `each1' from (irb):54 from /usr/bin/irb:12:in `&lt;main&gt;' </code></pre> <p>The version that delegates the block to the underlying iterable actually returns an enumerator if no block is given, which is very nice. It allows us to write stuff like this:</p> <pre><code>irb(main):055:0&gt; Test.new([1,2,3]).each2.map { |x| x + 1 } =&gt; [2, 3, 4] </code></pre> <p>To achieve the same with our explicit version, we'd have to adapt it like this:</p> <pre><code>def each1 return enum_for(:each1) unless block_given? @items.each { |i| yield i } end </code></pre> <p>Which is even more verbose. Bottomline: Delegate the block to an underlying enumerable whenever possible, to save yourself from code duplication and from subtle gotchas like these.</p> <p>By the way, now that you realize the two-folded nature of your <code>each</code> method, it would make sense to name it differently. For example, you could follow the example of methods like <code>String#chars</code> or <code>IO#lines</code> and call your method <code>items</code>:</p> <pre><code>def items(&amp;block) @items.each(&amp;block) end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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