Prerequisite: Ruby Range Operator
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.
[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.
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.
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(===).
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.
Z Y X W
- Private Classes in Ruby
- Ruby | Matrix cofactor() function
- Ruby Integer odd? function with example
- Ruby Integer div() function with example
- Ruby | Symbol to_s function
- Ruby | Set replace() function
- Ruby | Set reset() function
- Ruby For Beginners
- Ruby | Array Concatenation using (+) function
- Ruby | at() function
- Ruby Float to_r() method with example
- Ruby | Keywords
- Ruby | Exception Class and its Methods
- Ruby | String inspect Method
- Ruby | Numeric imaginary() function
- Ruby | Numeric i() function
- Ruby | Numeric fdiv() function
- Ruby | String hex Method
- Ruby | String include? Method
- Ruby | Hash each_pair() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : nidhi_biet