Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Ruby Dictionary

  1. Home
  2. Ruby Dictionary
  3. Numeric.times / upto / downto / step

Numeric.times / upto / downto / step

These are iteration methods available on integers. You can loop a specified number of times, or iterate over a range of numbers in ascending or descending order.

Syntax

# Repeats n times (from 0 to n-1).
n.times { |i| process }

# Counts up from start to stop, incrementing by 1 each time.
start.upto(stop) { |i| process }

# Counts down from start to stop, decrementing by 1 each time.
start.downto(stop) { |i| process }

# Counts from start to stop, incrementing by step each time.
start.step(stop, step) { |i| process }

Method list

MethodDescription
n.times { |i| }Repeats n times, passing integers from 0 to n-1 into the block.
start.upto(stop) { |i| }Counts up from start to stop by 1. Stops when the value exceeds stop.
start.downto(stop) { |i| }Counts down from start to stop by 1. Stops when the value goes below stop.
start.step(stop, step) { |i| }Iterates from start to stop in increments of step. Floating-point steps are supported.

Sample code

# times: repeats a specified number of times.
3.times { |i| print "#{i} " }
puts  # 0 1 2

# You can omit the block variable if you don't need the index.
3.times { print "★ " }
puts  # ★ ★ ★

# upto: iterates in ascending order.
1.upto(5) { |i| print "#{i} " }
puts  # 1 2 3 4 5

# downto: iterates in descending order.
5.downto(1) { |i| print "#{i} " }
puts  # 5 4 3 2 1

# step: iterates with a custom step value.
1.step(10, 2) { |i| print "#{i} " }
puts  # 1 3 5 7 9

# Floating-point steps are also supported.
0.0.step(1.0, 0.25) { |f| print "#{f} " }
puts  # 0.0 0.25 0.5 0.75 1.0

# Practical example: countdown.
puts "Countdown starts!"
5.downto(1) { |i| puts "#{i}..." }
puts "Blastoff!"

Overview

In Ruby, integers themselves have iterator methods, so you can write simple loops without using for or while. This is because Ruby follows the design philosophy that "everything is an object."

times passes an index (starting from 0) into the block. If you don't need the index, you can omit the block variable. upto and downto each iterate from a start value to an end value in steps of 1.

If the start value is greater than the stop value when using upto, or if stop is greater than start with a negative step in step, the block will never execute. Make sure the intended range is correct before using these methods.

You can also loop over a range object using Range#step. For integer predicate methods, see Integer#even? / odd? / zero?.

If you find any errors or copyright issues, please .