Ruby ranges depict a set of values with a beginning and an end. Values of a range can be numbers, characters, strings or objects. It is constructed using
start_point..end_point,
start_point...endpoint literals, or with
::new. It provides the flexibility to the code and reduce the size of code.
Example:
Output:
[7, 8, 9, 10]
[7, 8, 9]
Ruby provides the 3 types of ranges as follows:
- Ranges as Sequences
- Ranges as Conditions
- Ranges as Intervals
Ranges as Sequences
This is a general and easy way to define the ranges in Ruby to produce successive values in the sequence. It has a start point and an end point. Two operators are used for creating ranges, one is
Double Dot (..) operator and the another one is
Triple Dot (…) operator.
Example:
Output:
false
Maximum value = 8
Minimum value = 6
In Loop 6
In Loop 7
In Loop 8
Ranges as Conditions
Ranges can also be defined as conditional expressions in looping. Here conditions are enclosed within the start and end statements.
Example:
Output:
Lies Between 4000 and 5000
Ranges as Intervals
Ranges can also be defined in terms of intervals to check that the given value falls within the interval or not. It is represented by
equality operator(===).
Example:
Output:
D lies in the range of A to Z
77 lies in the range of 1 to 100
Note: In Ruby, if you are trying to use reverse range operator then nothing will be returned. Because in the range operators if the right side value is small than the left side value then they returned nothing. In order
to print a reverse order of given range, always use the
reverse() method with range operators.
Output:
Z
Y
X
W