Ruby

Search for '{{search_term}}'

Range in Ruby

CMOS is the Code-Maven Open Source podcast that also includes video interviews. Subscribe to this feed RSS feed with your Podcast listener app or via iTunes iTunes.

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

..

examples/ruby/range_two.rb

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.

examples/ruby/range_three.rb

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.

examples/ruby/range_two_wrong.rb

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:

examples/ruby/range_two_reverse.rb

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:

examples/ruby/range_letters.rb

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:

examples/ruby/range_chars.rb

for i in 'Z'..'a'
   puts i
end

Z
[
\
]
^
_
`
a

Range with variables

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

examples/ruby/range_var.rb

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

Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus