a. If its length is less than
3(this is true, since length is currently
0), we push a new random number into it.
endstatement paired with an
if, it proceeds forward and continues to execute the rest of the code (whether the
ifcondition was true or not).
ahas one element in it and
ifkeyword swapped for another keyword —
whileworks almost exactly like
if— it evaluates the expression next to it, and if it is true, it executes the code up until the
end; if not, it ignores the code up until the
end, the execution of the program jumps back up to the
whilestatement. Then the condition is evaluated again. If it is still true, then the code is executed again. And then the execution of the program jumps back up to the
whilestatement again. Etc.
end, we jump back up to the
a.length < 3again — still true, since
1 < 3
2 < 3? Yep, so we do it again.
3 < 3? Nope, so now we skip down to the end and continue
lenends up being
rails server, you basically started a program that went into an infinite loop of listening for web requests so that it could send back responses (and that's why you have to force it to shut down with Ctrl+C).
Arrays, and we usually need to loop across (or "iterate over") the array and do some work with each element in the array (like draw some nice HTML around it). So we need to get really good at iterating over arrays.
whilestatement, but Ruby gives us an easier way.
Arrays, let me instead just show you a purpose-built
Arraymethod that we're going to use 1000 times a day:
app/controllers/programs_controller.rband view the output at
https://ruby-intro-[YOUR CLOUD 9 USERNAME].c9users.io/second:
dokeyword next to it.
dokeyword has a matching
endkeyword, and the code to be repeated goes between them. (The whole thing from
endis known as a "block".) I just type the matching
endas soon as I type the
doso that I don't forget it, just the same as when I type an opening tag in HTML.
dokeyword, we put vertical bars known as "pipes" —
| |. Within the pipes, we choose a name that we want to use to refer to each element in the list as we are looping through it. In this case, I chose "
num". (This is known as a "block variable".)
endblock, I used the variable
numwhile writing the code I want executed for each element in the list.
.eachtakes care of all of that.
whileis neat to know about, the most important looping method that you need to understand right now is
|num|. It takes some practice. Try to remember that it's just a name that we make up for use within the
endblock to refer to each element in the array as the loop is being executed. I could have called it
zebraif I wanted to, and behind the scenes, Ruby would have assigned each element in the list to the variable
zebraas we got to its turn.
https://ruby-intro-[YOUR CLOUD 9 USERNAME].c9users.io/third. I've provided a variable for you,
numbers, which has an array in it containing the first 999 natural numbers.