Note that there are some explanatory texts on larger screens.

plurals
  1. POWhile Loops in Ruby and Converting to a Function
    primarykey
    data
    text
    <p>I'm on <a href="http://ruby.learncodethehardway.org/book/ex33.html" rel="nofollow">Chapter 33</a> of Learn Ruby the Hard Way.</p> <p>Extra credit exercise 1 asks:</p> <blockquote> <p>Convert this while loop to a function that you can call, and replace 6 in the test (i &lt; 6) with a variable.</p> </blockquote> <p>The code:</p> <pre><code>i = 0 numbers = [] while i &lt; 6 puts "At the top i is #{i}" numbers.push(i) i = i + 1 puts "Numbers now: #{numbers}" puts "At the bottom i is #{i}" end puts "The numbers: " for num in numbers puts num end </code></pre> <p>My attempt:</p> <pre><code>i = 0 numbers = [] def loops while i &lt; 6 puts "At the top i is #{i}" numbers.push(i) i = i + 1 puts "Numbers now: #{numbers}" puts "At the bottom i is #{i}" end end loops puts "The numbers: " for num in numbers puts num end </code></pre> <p>As you can see, I got as far as trying to make the block into a function, not yet making the 6 a variable. </p> <p>Error:</p> <pre><code>ex33.rb:5:in `loops': undefined local variable or method `i' for main:Object (Na meError) from ex33.rb:15:in `&lt;main&gt;' from ex33.rb:15:in `&lt;main&gt;' </code></pre> <p>What am I doing wrong?</p> <p>EDIT: Okay, improved it a little. Now the numbers variable is out of scope...</p> <pre><code>def loops (i, second_number) numbers = [] while i &lt; second_number puts "At the top i is #{i}" i = i + 1 numbers.push(i) puts "Numbers now: #{numbers}" puts "At the bottom i is #{i}" end end loops(0,6) puts "The numbers: " for num in numbers puts num 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. 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