Ruby 2 Ranges

The first and perhaps most natural use of ranges is to express a sequence. Sequences have a start point, an end point, and a way to produce successive values in the sequence. In Ruby, these sequences are created using the ".." and "..." range operators. The two dot form creates an inclusive range, and the three-dot form creates a range that excludes the specified high value. In Ruby ranges are not represented internally as lists: the sequence 1..100000 is held as a Range object containing references to two Fixnum objects. Refer program p021ranges.rb. If you need to, you can convert a range to a list using the to_a method.
  1. (1..10).to_a -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
Ranges implement methods that let you iterate over them and test their contents in a variety of ways.
  1. # p021ranges.rb  
  2. =begin  
  3.   Sequences have a start point, an end point, and a way to  
  4.   produce successive values in the sequence  
  5.   In Ruby, sequences are created using the ".." and "..."  
  6.   range operators.  
  7.   The two dot form creates an inclusive range.  
  8.   The three-dot form creates a  range that excludes the specified  
  9.   high value  
  10.   The sequence 1..100000 is held as a Range object  
  11. =end  
  12. digits = -1..9  
  13. puts digits.include?(5)          # true  
  14. puts digits.min                  # -1  
  15. puts digits.max                  # 9  
  16. puts digits.reject {|i| i < 5 }  # [5, 6, 7, 8, 9]  
Another use of the versatile range is as an interval test: seeing if some value falls within the interval represented by the range. We do this using ===, the case equality operator.
  1. (1..10) === 5       -> true  
  2. (1..10) === 15      -> false  
  3. (1..10) === 3.14159 -> true  
  4. ('a'..'j') === 'c'  -> true  
  5. ('a'..'j') === 'z'  -> false