How to Use the Ruby times Method

09/24/2021

Contents

In this article, you will learn how to use the Ruby times method.

Using the times method

The Ruby times method is a built-in method that can be used with integers to execute a block of code a specified number of times.

The basic syntax of the times method is as follows:

integer.times do
  # code to be executed
end

Here, integer represents the number of times the block of code will be executed. The block of code is defined using the do…end syntax, and is executed integer times.

For example, if we wanted to print the phrase “Hello, world!” five times using the times method, we could write:

5.times do
  puts "Hello, world!"
end

This would output:

Hello, world!
Hello, world!
Hello, world!
Hello, world!
Hello, world!

In addition to the basic syntax, there are a few variations of the times method that can be used to achieve different results.

Using a Block Parameter

If we want to know which iteration of the loop we are currently on, we can use a block parameter. This is a variable that is assigned the value of the current iteration. The block parameter is defined using the |variable| syntax. For example, if we wanted to print the numbers 1 through 5 using the times method, we could write:

5.times do |i|
  puts i + 1
end

This would output:

1
2
3
4
5

Using a Single-Line Block

If the block of code we want to execute is only a single line, we can use a single-line block. This is a shorter syntax that allows us to write the block on the same line as the times method. For example, if we wanted to print the numbers 1 through 5 using a single-line block, we could write:

5.times { |i| puts i + 1 }

This would output:

1
2
3
4
5

Using the Return Value

The times method returns the integer that it was called on. This means we can use the return value in our code. For example, if we wanted to sum the numbers 1 through 5, we could write:

sum = 0
5.times do |i|
  sum += i + 1
end
puts sum

This would output:

15