{"data":{"wordpressPost":{"id":"69b2a38b-3ece-5c90-b811-b1097b30bbec","title":"Ruby Loops Demystified","slug":"194","content":"<h1></h1>\n<p><em>Note: This explanation of looping is geared towards absolutely-100%-new programmers. Consider yourself warned. Also, I highly recommend typing the examples into a new Ruby file and then running it to see the output and get a better feel for what is going on. Really &#8211; it helps!</em></p>\n<p>Looping is a fundamental concept in computer programming. It is often necessary to repeat the same set of instructions multiple times, and rather than write those instructions over and over and over, you can use a loop to automate that repeating.</p>\n<p>Often, you don&#8217;t even know exactly how many times you will need to repeat something, so inside the loop you can include a way for the computer to figure it out for you. So instead of saying &#8220;Do this 5 times,&#8221; you&#8217;ll say &#8220;Do this x times.&#8221; An added benefit here is that if you need to change the number of times those instructions are repeated, you&#8217;ve built some flexibility into the code.</p>\n<p>But I digress.</p>\n<p>There are multiple ways to loop over code in Ruby, including both &#8220;language constructs&#8221; (built in syntax for expressing logic) like the reserved keywords<strong>while</strong>, <strong>until</strong>, and <strong>for</strong>; as well as &#8220;methods&#8221; (ways to do something to something) like <strong>.each()</strong> and <strong>.times()</strong>.</p>\n<p>Perhaps the best way to explain these different kinds of loops is to first differentiate them by how they work.</p>\n<h2>Conditional Loops</h2>\n<p>Conditional loops execute the specified code <em>until a certain condition is met</em>. For example, you want to add candles to a birthday cake <em>until</em> you&#8217;ve reached the age of the birthday child. (You can also execute the specified code <em>while a certain condition is still the case</em> &#8211; we&#8217;ll see that in a second.)</p>\n<p>Here you find yourself with a true or false situation: is the number of candles equal to the age yet? No? (False?) Okay, let&#8217;s add another candle. Now is the number of candles equal to the age? (True or false?) And so on.</p>\n<h3>Until Loops</h3>\n<p>Ruby has a keyword that is perfect for this candle-adding situation, and not surprisingly, it is <strong>until</strong>. Ruby likes its mnemonic word choices, so that it almost seems like you&#8217;re speaking English to the computer. (Other languages don&#8217;t necessarily work this way.)</p>\n<p>There are two ways to write this loop: as a conditional &#8220;statement&#8221; or as a conditional &#8220;modifier.&#8221;</p>\n<p><em>Statement syntax</em> for our birthday example would be:</p>\n<blockquote>\n<pre>candles = 0  <em>#because you haven't put any candles on the cake yet</em>\r\nage = 5  <em>#have to specify the age or the computer won't know when to stop adding candles!</em>\r\n\r\nuntil candles == age  <em>#here we specify the condition we want to meet: candles equals age</em>\r\n   candles = candles + 1  <em>#here we add 1 to the number of candles, and this is the part \r\n   that gets repeated until the above condition (does the # of candles equal the age?) is met</em>\r\nend  <em>#\"end\" tells the computer that the until loop stops here</em></pre>\n</blockquote>\n<p><em>Modifier syntax</em> would look like:</p>\n<p>&nbsp;</p>\n<blockquote>\n<pre>candles = 0\r\nage = 5\r\n\r\ncandles += 1 until candles == age  <em>#add to candles until candles equals age</em></pre>\n</blockquote>\n<p><em>(Fyi: &#8220;+=&#8221; is a shorthand for &#8220;candles = candles + 1&#8221;. Blew my mind first time I saw that.)</em></p>\n<p>As you can see, assuming the code you&#8217;re repeating isn&#8217;t super complicated, the modifier version is much simpler and easier to read than the statement version.</p>\n<p>And because Ruby seems to always have at least three different ways to do the exact same thing, you can use another version of modifier syntax as well:</p>\n<blockquote>\n<pre>candles = 0\r\nage = 5\r\n\r\nbegin\r\n  candles += 1\r\nend until candles == age  <em>#this seems a bit more confusing, in my opinion</em></pre>\n</blockquote>\n<h3>While Loops</h3>\n<p>Related to the <strong>until</strong> loop is the <strong>while</strong> loop. It also uses a condition to decide how many times to do something. <strong>until</strong> does something <em>until</em> the condition is true (so it starts out &#8220;false&#8221;), but <strong>while</strong> is the opposite:</p>\n<p><em>While</em> any of the candles are still lit, keep blowing.</p>\n<p>In code, this looks like either (statement syntax):</p>\n<blockquote>\n<pre>lit_candles = 5\r\n\r\nwhile lit_candles &gt; 0\r\n  lit_candles -= 1  <em>#keep blowing!</em>\r\nend</pre>\n</blockquote>\n<p>or (modifier syntax):</p>\n<blockquote>\n<pre>lit_candles = 5\r\nlit_candles -= 1 while lit_candles &gt; 0</pre>\n</blockquote>\n<h3>Until vs While</h3>\n<p>So what&#8217;s the difference between these? Aren&#8217;t they pretty much two different ways to accomplish the same thing? Couldn&#8217;t I just say &#8220;until lit_candles is 0, keep blowing&#8221;?</p>\n<p>Yes. Yes you could. In fact, a lot of other languages don&#8217;t even have an <strong>until</strong> option, they only have <strong>while</strong>. The reason we have two options here is because Ruby was designed to read more like English than some of the older programming languages.</p>\n<p>When you&#8217;re choosing whether to use <strong>while</strong> or <strong>until</strong>, just ask yourself how you would state the situation in plain ol&#8217; English. &#8220;I want to nap <em>until</em> 2:00.&#8221;&#8221; &#8220;<em>While</em> I&#8217;m at work I want to check my email hourly.&#8221;&#8221; Whichever option makes it easier to read and understand, that&#8217;s the option you should choose.</p>\n<p>So that&#8217;s conditional loops, but what about iterative loops?</p>\n<h2>Iterative Loops</h2>\n<p>Here, instead of having a true/false condition that we&#8217;re working with, we simply want to do something a certain number of times. We want to <em>iterate</em>over a collection of data, repeating an action as many times as there are bits of info in our collection.</p>\n<h3>For Loops</h3>\n<p>To keep things simple, I&#8217;ll use an array in the examples, which is pretty much just a list of things. For every &#8220;thing&#8221; in the list, we do something once. In fact, the syntax here uses <strong>for</strong>:</p>\n<blockquote>\n<pre>presents = ['coloring book', 'stuffed animal', 'bouncy ball', 'puzzle']  <em>#here we're \r\ntelling the computer what our array has listed inside: 'coloring book', 'stuffed animal', etc.</em>\r\n\r\nfor present in presents  <em>#see note below </em>\r\n  puts present  <em>#put each item on the screen where we can see it</em>\r\nend  <em>#again, saying \"end\" lets the computer know that's all of the code it needs to repeat</em></pre>\n</blockquote>\n<p>Note: Ruby doesn&#8217;t know what a &#8220;present&#8221; is &#8211; this is just the name I chose to represent each and every item in the list as we go through that list. I could have chosen &#8220;a&#8221; or &#8220;x&#8221; or &#8220;hurricane&#8221; and it would still work &#8211; the names I chose just make more sense in this (birthday party) context than &#8220;hurricane&#8221; does. It&#8217;s like in algebra, where &#8220;x&#8221; and &#8220;y&#8221; don&#8217;t actually have any inherent value, they&#8217;re more like placeholder names.</p>\n<p>Ruby also doesn&#8217;t know what a &#8220;candle&#8221; is, or &#8220;age,&#8221; or &#8220;lit_candles&#8221; &#8211; these are all just names that I&#8217;ve used to help someone reading the code understand what I&#8217;m talking about. Unfortunately, very new beginning coders can be confused by this because they haven&#8217;t memorized all the words that Ruby <em>does</em>know. For this reason, it can be a good idea to have a list of keywords handy so you can double check when you&#8217;re not sure! (If you didn&#8217;t understand this until now, go re-read the code above and see if it makes more sense.)</p>\n<h3>Looping Methods</h3>\n<p>The <strong>for</strong> loop example given above is all well and good, works totally fine, but Ruby has some additional, special ways to loop over your data. The two most basic ones are <strong>each</strong> and <strong>times</strong>.</p>\n<h4>Each Loops</h4>\n<p><strong>each</strong> does very nearly the exact same thing as <strong>for</strong>, so unless you know you <em>need</em> to use <strong>for</strong>, you should try to use <strong>each</strong> instead (more about that in a bit):</p>\n<blockquote>\n<pre>presents = ['coloring book', 'stuffed animal', 'bouncy ball', 'puzzle']\r\n\r\npresents.each do |present|  <em>#for each item in presents do:</em>\r\n  puts present  <em>#put the item on the screen</em>\r\nend</pre>\n</blockquote>\n<p>We have to give some name to specify &#8220;individual thing in the list,&#8221; and with the <strong>each</strong> method, our iterator variable &#8220;present&#8221; goes between two pipes: | | (as opposed to the <strong>for</strong> syntax which puts it between <strong>for</strong> and <strong>in</strong>).</p>\n<h4>Each vs For</h4>\n<p>So which version should you use? It is considered more <a href=\"http://learncodethehardway.org/blog/AUG_19_2012.html\" target=\"new\">idiomatic</a> &#8211; &#8220;more Ruby&#8221; &#8211; to use <strong>each</strong> than to use <strong>for</strong>.</p>\n<p>The reason why, though, might be a little too much for an absolute beginner to wrap their head around: <strong>each</strong> creates an iterator variable (ie &#8220;present&#8221; in our presents example) that lives <em>only</em> within the &#8220;scope&#8221; (context) of the <strong>each</strong> &#8220;block&#8221; (the code between <strong>do</strong> and <strong>end</strong>).</p>\n<p>But, for now, you don&#8217;t actually have to understand the why of it. Just remember if you use <strong>each</strong> you&#8217;re less likely to accidentally get yourself in trouble: when using <strong>each</strong>, the iterator variable goes away once you&#8217;re done with that bit of code, but <strong>for</strong>&#8216;s iterator variable persists and so it could accidentally alter something you don&#8217;t want to alter. Plus&#8230; it&#8217;s what people expect you to do. Keep the peoples happy.</p>\n<h4>Times Loops</h4>\n<p>The <strong>times</strong> method is a similar approach to <strong>each</strong>, in that it&#8217;s also more idiomatic:</p>\n<blockquote>\n<pre>3.times do  <em>#for a certain number of times, do the following:</em>\r\n  puts \"Happy birthday!\"\" \r\nend</pre>\n</blockquote>\n<p>Again, one of the important ideas behind Ruby is that the code should be easy to understand. The above is certainly easier to read than, for example, our candle-inserting <strong>until</strong> loop (in this particular example&#8217;s <strong>times</strong> loop, anyway &#8211; you could definitely make it more complicated if you need to do something more complicated!)</p>\n<h2>Loop de Loop</h2>\n<p>And there we have our primary ways of repeating chunks of code in Ruby:</p>\n<p>&nbsp;</p>\n<ul>\n<li><strong>until</strong></li>\n<li><strong>while</strong></li>\n<li><strong>for</strong></li>\n<li><strong>each</strong></li>\n<li><strong>times</strong></li>\n</ul>\n<p>&nbsp;</p>\n<p>You will get lots of practice with these, because they really are used ALL THE TIME. Some additional resources in case you still have questions:</p>\n<p>&nbsp;</p>\n<ul>\n<li><a href=\"http://www.humblelittlerubybook.com/book/html/chapter3.html\" target=\"new\">http://www.humblelittlerubybook.com/book/html/chapter3.html</a></li>\n<li><a href=\"http://www.tutorialspoint.com/ruby/ruby_loops.htm\" target=\"new\">http://www.tutorialspoint.com/ruby/ruby_loops.htm</a></li>\n<li><a href=\"http://stackoverflow.com/questions/3294509/for-vs-each-in-ruby?rq=1\" target=\"new\">http://stackoverflow.com/questions/3294509/for-vs-each-in-ruby?rq=1</a></li>\n<li><a href=\"http://stackoverflow.com/questions/5677081/ruby-difference-between-a-for-loop-and-an-each-loop\" target=\"new\">http://stackoverflow.com/questions/5677081/ruby-difference-between-a-for-loop-and-an-each-loop</a></li>\n<li><a href=\"http://ruby.about.com/od/rubyfeatures/a/loops_2.htm\" target=\"new\">http://ruby.about.com/od/rubyfeatures/a/loops_2.htm</a></li>\n<li><a href=\"http://davidraffauf.com/2013/01/30/writing-more-idiomatic-ruby-code/\" target=\"new\">http://davidraffauf.com/2013/01/30/writing-more-idiomatic-ruby-code/</a></li>\n</ul>\n","date":"June 24, 2014","categories":[{"name":"ones and zeros","slug":"ones-and-zeros"}],"tags":null,"author":{"name":"jessica","slug":"jessica"}}},"pageContext":{"id":"69b2a38b-3ece-5c90-b811-b1097b30bbec"}}