Range in Ruby

Ruby has two operators to generate a range of values. .. is inclusive and ... is exclusive.

..

for i in 0..3 puts i end

Will generate

0 1 2 3

including the beginning and the end similar to how the range in Perl works.

...

If we use 3 dots instead of two, then the range will include the lower limit, but not the higher limit. Similar to how range in Python works.

for i in 0...3 puts i end
0 1 2

reverse range

If the limit on the left hand side is higher than on the right hand side, the range operator won't return any values.

for i in 7 .. 4 puts i end

It does not return any value.

As an alternative we can create a growing list of number and then call the reverse method on them. For this however first we need to convert the rnage to an array:

for i in (4..7).to_a.reverse puts i end

printing:

7 6 5 4

Range of letters

In additonal to ceating ranges of numbers, Ruby can also create a range of letters:

for i in 'a'..'d' puts i end
a b c d

Range of characters

Not only that, but we can use any two characters in the visible part of the ASCII table:

for i in 'Z'..'a' puts i end
Z [ \ ] ^ _ ` a

Range with variables

We can also use variables as the lower and upper limits:

x = 3 y = 6 for i in x .. y puts i end

timestamp: 2015-09-24T23:30:01 tags:

  • ..
  • ...
  • to_a
  • reverse