Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, I'll explain why you wouldn't want to use <code>for</code>, and then explain why you might.</p> <p>The main reason you wouldn't want to use <code>for</code> is that it's un-idiomatic. If you use <code>each</code>, you can easily replace that <code>each</code> with a <code>map</code> or a <code>find</code> or an <code>each_with_index</code> without a major change of your code. But there's no <code>for_map</code> or <code>for_find</code> or <code>for_with_index</code>.</p> <p>Another reason is that if you create a variable within a block within <code>each</code>, and it hasn't been created before-hand, it'll only stay in existance for as long as that loop exists. Getting rid of variables once you have no use for them is a good thing.</p> <p>Now I'll mention why you might want to use <code>for</code>. <code>each</code> creates a closure for each loop, and if you repeat that loop too many times, that loop can cause performance problems. In <a href="https://stackoverflow.com/a/10325493/38765">https://stackoverflow.com/a/10325493/38765</a> , I posted that using a <code>while</code> loop rather than a block made it slower. </p> <pre><code>RUN_COUNT = 10_000_000 FIRST_STRING = "Woooooha" SECOND_STRING = "Woooooha" def times_double_equal_sign RUN_COUNT.times do |i| FIRST_STRING == SECOND_STRING end end def loop_double_equal_sign i = 0 while i &lt; RUN_COUNT FIRST_STRING == SECOND_STRING i += 1 end end </code></pre> <p><code>times_double_equal_sign</code> consistently took 2.4 seconds, while <code>loop_double_equal_sign</code> was consistently 0.2 to 0.3 seconds faster.</p> <p>In <a href="https://stackoverflow.com/a/6475413/38765">https://stackoverflow.com/a/6475413/38765</a> , I found that executing an empty loop took 1.9 seconds, whereas executing an empty block took 5.7 seconds.</p> <p>Know why you wouldn't want to use <code>for</code>, know why you would want to use <code>for</code>, and only use the latter when you need to. Unless you feel nostalgic for other languages. :)</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