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