How to Use times Method in Ruby: Simple Looping Explained
In Ruby,
times is a method used to run a block of code a specific number of times. You call it on an integer like 5.times and provide a block that runs that many times. It’s a simple way to repeat actions without writing a full loop.Syntax
The times method is called on an integer and takes a block of code to execute repeatedly. The block can optionally receive the current iteration index starting from 0.
integer.times { block }- runs the blockintegertimes.- The block can use a parameter to get the current count (0 to integer-1).
ruby
5.times do |i| puts "Iteration number: #{i}" end
Output
Iteration number: 0
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Example
This example shows how to print a message 3 times using times. It demonstrates the block receiving the iteration index.
ruby
3.times do |count| puts "Hello! This is message number #{count + 1}." end
Output
Hello! This is message number 1.
Hello! This is message number 2.
Hello! This is message number 3.
Common Pitfalls
One common mistake is forgetting that the block index starts at 0, not 1, which can cause off-by-one errors. Another is calling times on a non-integer, which will cause an error. Also, using times without a block does nothing useful.
ruby
3.times do |i| puts i # prints 0,1,2 end # Wrong: expecting 1,2,3 without adjustment # Correct way to start from 1: 3.times do |i| puts i + 1 end
Output
0
1
2
1
2
3
Quick Reference
Use times to repeat code easily when you know how many times to run it. The block index starts at 0. It works only on integers.
| Usage | Description |
|---|---|
5.times { code } | Run code 5 times without index |
5.times do |i| ... end | Run code 5 times with index i from 0 to 4 |
0.times { code } | Does not run the block at all |
non_integer.times | Raises error - only integers support times |
Key Takeaways
Use
times on an integer to repeat a block that many times.The block index starts at 0, so adjust if you want counting from 1.
Only integers support
times; using other types causes errors.Without a block,
times does nothing useful.It’s a simple and readable way to run loops when count is fixed.