Ranges

Just as a list is a convenient way to group together related values, a range is a shortcut to representing lists of numbers. To represent a bunch of sequential numbers in a list, you'd have to type `[1, 2, 3, 4, 5, ...]`. What if you wanted 50 numbers? Or 1,000? Ranges make this easier by just listing the starting and ending number.

The range `1..100` is equivalent to a list of all the whole numbers from 1 to 100. This includes both 1 and 100. Ranges can also go in reverse. The range `20..-10` represents all whole numbers starting at 20 down to -10.

Using the collect function we can convert a range into a list to inspect what numbers it contains:

``````collect(2..5)
collect(5..2)
collect(-2..2)``````
``````[2, 3, 4, 5]
[5, 4, 3, 2]
[-2, -1, 0, 1, 2]``````

Step Values

By default, ranges increase by one from their start value. For ranges that are reversed, they decrease by one instead. This is called the "step" value. By changing the step value, you can control which numbers are part of the range.

``````collect(2..10 step 2)
collect(0..300 step 100)
collect(0..1 step 0.25)
collect(2..-6 step -2)``````
``````[2, 4, 6, 8, 10]
[0, 100, 200, 300]
[0, 0.25, 0.5, 0.75, 1]
[2, 0, -2, -4, -6]``````

If the step value doesn't stop exactly on the end of the range, that last value isn't included.

``````collect(2..10 step 3)
collect(0..1 step .3)``````
``````[2, 5, 8]
[0, 0.3, 0.6, 0.9]``````

Using Ranges

Ranges are handy when used with loops. Perhaps you want to loop through five times, but using only even numbers.

``````for value in 2..10 step 2 {
value / 2
}``````
``````

``````

Here's a practical example of where ranges can really shine. Let's say you want to estimate the return on your investments each year for the next three years. Let's walk through how to do that.

First, let's look at a simplified formula for calculating compound interest:

``````principal = \$10k
rate = 5%
years = 2
principal × (1 + rate)^years``````
``````\$10,000
5%
2
\$11,025``````

But we don't just want to know the value after two years. We were trying to find the result for the next three years. Let's change the `years` variable to be a list:

``````principal = \$10k
rate = 5%
years = [1, 2, 3]
principal × (1 + rate)^years``````
``````\$10,000
5%
[1, 2, 3]
[\$10,500, \$11,025, ...]``````

That works great. But what if we wanted to know the next ten years? The next 50? By changing `years` to be a range instead of a list, you can control which years you want to use as milestones for estimating investments.

``````principal = \$10k
rate = 5%
years = 5..20 step 5
principal × (1 + rate)^years``````
``````\$10,000
5%
5 .. 20 step 5
[\$12,762.82, \$16,288.95, ...]``````

Didn't find what you were looking for?