Ruby Range
Ranges are everywhere: a to z, 0 to 9, and so on. Ruby supports ranges and allows us to use ranges in different ways:
- Ranges as Sequences
- Ranges as Conditions
- Ranges as Intervals
Ranges as Sequences
The first and most common use of ranges is to express sequences. Sequences have a start point, an end point, and a way to produce successive values in the sequence.
Ruby uses''..''and''...''range operators to create these sequences. The two-dot form creates a range that includes the specified highest value, and the three-dot form creates a range that does not include the specified highest value.
The sequence 1..100 is aRangeobject that contains twoFixnumreferences to objects. If necessary, you can useto_amethod to convert the range to a list. Try the following example:
Example
Try it »
The output of the above example is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ["bar", "bas", "bat"]
Ranges implement methods that let you iterate over them and check their contents in various ways:
Example
Try it »
Running the above example produces:
true 最小值为 0 最大值为 9 不符合条件的有 [5, 6, 7, 8, 9] 在循环中 0 在循环中 1 在循环中 2 在循环中 3 在循环中 4 在循环中 5 在循环中 6 在循环中 7 在循环中 8 在循环中 9
Ranges as Conditions
Ranges can also be used as conditional expressions. For example, the following code snippet prints lines from standard input, where the first line of each set contains the wordstart, and the last line contains the wordend.:
Ranges can be used in case statements:
Example
Try it »
The above example outputs:
Passing score
Ranges as Intervals
The last use of ranges is interval detection: checking whether a specified value falls within a specified range. This requires the === equality operator to perform the calculation.
Example
Try it »
The above example outputs:
5 在 (1..10)
c 在 ('a'..'j')
Other Extensions