Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
The times iterator will take a number and execute the statements in the block that number of times. The times iterator optionally takes an argument and, just like array indices, starts at 0.
Code Samples
Using a number, we can iterate that amount of times:
5.times do
puts "Hello!"
end
This will print "Hello!" to the screen 5 times.
The times
method also can take a single argument:
5.times do |item|
puts "Hello! #{item}"
end
Just like an array index, the times
index starts at 0.
-
0:00
Another kind of iterator in Ruby that works specifically with
-
0:04
integers is the times iterator.
-
0:07
The times iterator will take a number,
-
0:10
execute the statements in the block that number of times.
-
0:14
The times iterator, optionally,
-
0:16
takes an argument, and, just like array indexes, starts at zero.
-
0:22
Let's see how that works now using WorkSpaces.
-
0:25
Okay, using a Ruby workspace let's go ahead and create a new file.
-
0:29
We'll call this times.rb.
-
0:31
The times method is really easy to use.
-
0:36
We'll take any number, let's use 5 as an example and
-
0:40
use a dot like we're going to call a method and then we use the word times.
-
0:48
From there, we write a do end block like we're used to.
-
0:52
Now let's just type puts hello.
-
0:57
Now we can run this, using ruby times.rb.
-
1:02
And we see that it prints hello five times.
-
1:10
And we can also send arguments into the times method.
-
1:16
Let's create a new file.
-
1:18
To test that out, we'll call it times with argument.rb.
-
1:24
And we'll write that just like we did the times loop.
-
1:29
So here we did five times.
-
1:34
Do end.
-
1:37
Now just like with other iterators and blocks,
-
1:40
if we want to send an argument to the block we do so by writing a pipe and
-
1:45
putting the local variable inside of the pipes.
-
1:50
The times method can take one argument into the block
-
1:56
and we'll go ahead and print that out.
-
2:02
And if we run ruby times_with_argument.rb.
-
2:06
We can see, we get all of these different arguments as the item and
-
2:11
it starts with zero just like array indexes.
-
2:16
Try practicing with the times iterator on your own now, using WorkSpaces.
You need to sign up for Treehouse in order to download course files.
Sign up