0
0
Rubyprogramming~5 mins

Times method for counted repetition in Ruby

Choose your learning style9 modes available
Introduction

The times method helps you repeat a task a certain number of times easily, without writing loops manually.

When you want to print a message multiple times.
When you need to run a block of code a fixed number of times.
When you want to create or fill a list with repeated values.
When you want to perform an action for each number from zero up to a limit.
Syntax
Ruby
number.times do |index|
  # code to repeat
end

The number is how many times you want to repeat.

The block between do and end runs each time.

Examples
Prints "Hello" 5 times without using the index.
Ruby
5.times do
  puts "Hello"
end
Prints the count from 0 to 2 using the index i.
Ruby
3.times do |i|
  puts "Count: #{i}"
end
Uses curly braces for a shorter block to print "Ruby" 4 times.
Ruby
4.times { puts "Ruby" }
Sample Program

This program prints "Step number" followed by the step count from 1 to 3.

Ruby
3.times do |i|
  puts "Step number #{i + 1}"
end
OutputSuccess
Important Notes

The index starts at 0 and goes up to one less than the number.

You can use times with or without the block parameter if you don't need the count.

Summary

times repeats code a set number of times.

Use the block parameter to get the current count starting at zero.

It makes repeating tasks simple and clean without writing loops manually.