learn-co-curriculum/looping-times
Objectives
Understand the
times
construct and how it implements loopingBuild a method using
times
Introduction
The next construct in our list is times
. There are two important distinctions to be mindful of when using times
. The first one is that it has to be called on an Integer (like 1
or 10000
). The second is that it executes the block a certain number of times, which is dependent on the number that it's called on. Let's look at the example below:
This outputs Penguins like to jump off icebergs!
five times in your Terminal.
Examples
Basic times
Example: Dinner Party
times
Example: Dinner PartyLet's take a look at some more complex examples:
You just had a wildly successful dinner party with seven of your very best friends. Then they went home and left you with all of the dishes. They will not be invited back.
Let's clean those dishes using the times
method:
Intermediate times
Example: Crime Spree
times
Example: Crime SpreeOkay, that's fine, but all we did was print some text––what if we wanted to change the value of a variable within a loop? Let's see how that works:
You are a jewel thief who has stolen one hundred (100) very valuable jewels (you are a really good jewel thief). But now you need to unload your stolen jewels from your bag into the safe in your secret hideout!
Advanced times
Example
times
ExampleThis is fun and all, but so far we've only printed text within the block of code within the loop. What if we wanted to do something more, say, keep track of the number of jewels we are hiding as we hide them?
Using the times
method
times
methodWe're still struggling to master that levitation charm. Since we need to keep practicing, let's write some code that allows us to puts
the phrase "Wingardium Leviosa" only seven times (instead of infinitely, like when we used just a plain loop
construct).
Instructions
Fork and clone this lab.
Run the test suite with the
learn
command.You'll be coding your solution in
times.rb
:
Fill out the content of the
using_times
method so that calling it willputs
the desired phrase,"Wingardium Leviosa"
seven times by using thetimes
keyword.
Last updated