Ruby - Introduction Ranges


To represent all the letters between A and Z, you could begin to create an array, like so:

x = ['A', 'B', 'C', 'D', 'E' .. and so on.. ] 

A range is represented in this way:


The Range class offers a simple way to convert a range into an array with to_a. This one-line example demonstrates:


('A'..'Z').to_a.each { |letter| print letter }


It converts the range 'A' to 'Z' into an array with 26 elements, each one containing a letter of the alphabet.

It iterates over each element using each, which you first used in the previous section on arrays, and passes the value into letter, which is then printed to the screen.

print method outputs the letters one after another on the same line, whereas puts starts a new line every time it's used.

Ruby Range is a class that represents a set of values defined by a starting value and an ending value.

Typically a range is defined using integers.

It may also be defined using other ordered values such as floating-point numbers or characters.

Values can be negative, and you should be careful that your starting value is lower than your ending value!

Here are a few examples:

a = (1..10) 
b = (-10..-1) 
c = (-10..10) 
d = ('a'..'z') 

You can specify ranges using three dots instead of two; this creates a range that omits the final value:

d = ('a'..'z')         # this two-dot range = 'a'..'z' 
e = ('a'...'z')        # this three-dot range = 'a'..'y' 

You can create an array of the values defined by a range using the to_a method, like this:


puts (1..10).to_a


to_a is not defined for floating-point numbers since the number of possible values between two floating-point numbers is not finite.

Related Topics