Home » Ruby Ranges

Ruby Ranges

Ruby range represents a set of values with a beginning and an end. They can be constructed using s..e and s…e literals or with ::new.

The ranges which has .. in them, run from beginning to end inclusively. The ranges which has … in them, run exclusively the end value.

Output:

Ruby rangers 1

Ruby has a variety of ways to define ranges.

  • Ranges as sequences
  • Ranges as conditions
  • Ranges as intervals

Ranges as Sequences

The most natural way to define a range is in sequence. They have a start point and an end point. They are created using either .. or … operators.

We are taking a sample range from 0 to 5. The following operations are performed on this range.

Example:

Output:

Ruby rangers 2


Ranges as Conditions

Ranges are also defined as conditional expressions. Different conditions are defined in a set of lines. These conditions are enclosed within start statement and end statement.

Example:

Output:

Ruby rangers 3


Ranges as Intervals

Ranges can also be defined in terms of intervals. Intervals are represented by === case equality operator.

Example:

Output:

Ruby rangers 4


Ruby Reverse Range

Ruby reverse range operator does not return any value. If left side value is larger than right side value in a range, no vlaue will be returned.

Example:

Nothing will be returned in the output for the above example.

To print a reverse order, you can use reverse method in a normal range as shown below.

Example:

Output:

Ruby rangers 5


Next TopicRuby iterators

You may also like