Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let's illustrate the point by an example:</p> <pre><code>results = [] (1..3).each do |i| results &lt;&lt; lambda { i } end p results.map(&amp;:call) # =&gt; [1,2,3] </code></pre> <p>Cool, this is what was expected. Now check the following:</p> <pre><code>results = [] for i in 1..3 results &lt;&lt; lambda { i } end p results.map(&amp;:call) # =&gt; [3,3,3] </code></pre> <p>Huh, what's going on? Believe me, these kinds of bugs are nasty to track down. Python or JS developers will know what I mean :)</p> <p>That alone is a reason for me to avoid these loops like the plague, although there are more good arguments in favor of this position. As Ben pointed out correctly, using the proper method from <a href="http://apidock.com/ruby/Enumerable"><code>Enumerable</code></a> almost always leads to better code than using plain old, imperative <code>for</code> loops or the fancier <code>Enumerable#each</code>. For instance, the above example could also be concisely written as</p> <pre><code>lambdas = 1.upto(3).map { |i| lambda { i } } p lambdas.map(&amp;:call) </code></pre> <blockquote> <p>I expand the question: Where else in Ruby do we see what apears do/end block delimiters, but there is actually no scope inside? Anything else apart from for ... do ... end?</p> </blockquote> <p>Every single one of the looping constructs can be used that way:</p> <pre><code>while true do #... end until false do # ... end </code></pre> <p>On the other hand, we can write every one of these without the <code>do</code> (which is obviously preferrable):</p> <pre><code>for i in 1..3 end while true end until false end </code></pre> <blockquote> <p>One more expansion of the question, is there a way to write for loop with curly braces { block }</p> </blockquote> <p>No, there is not. Also note that the term "block" has a special meaning in Ruby.</p>
    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