Integer#times
We'll continue today with another intuitive and expressive method in Ruby: Integer#times.
5.times do |i|
puts i
end
# Output:
# 0
# 1
# 2
# 3
# 4
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output:
// 0
// 1
// 2
// 3
// 4
Since times returns an Enumerator, we can leverage that by chaining map to create an array of a certain size with values derived from the index:
squares = 10.times.map { |i| i * i }
# => [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
const squares = Array.from({ length: 10 }, (_, i) => i * i);
// => [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
A personal favorite use case is spawning multiple threads to perform concurrent work:
NUMBER_OF_WORKERS = 5
threads = NUMBER_OF_WORKERS.times.map do
Thread.new do
# perform some work
end
end
results = threads.each(&:value)
Or how about generating some test data:
ten_users = 10.times.map do |i|
{
name: "User #{i}",
email: "user#{i}@example.com"
}
end
User.insert_all(ten_users)
Beautiful, isn't it?
History
The times method has been around in Ruby since at least version 1.8, though it was originally a method on Fixnum and Bignum, which were unified into Integer in Ruby 2.4.
As is becoming a pattern, we can trace the idea of a "times" API back to Smalltalk's timesRepeat as well as Lisp's dotimes. No recent languages appear to have a similar construct built-in, settling for conventional "computer language" like for ... instead.