Ruby Ranges

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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.

  1. puts (-5..-1).to_a       
  2. puts (-5...-1).to_a       
  3. puts ('a'..'e').to_a      
  4. puts ('a'...'e').to_a  

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:

  1. #!/usr/bin/ruby   
  2.   
  3. range = 0..5   
  4.   
  5. puts range.include?(3)   
  6. ans = range.min   
  7. puts "Minimum value is #{ans}"   
  8.   
  9. ans = range.max   
  10. puts "Maximum value is #{ans}"   
  11.   
  12. ans = range.reject {|i| i < 5 }   
  13. puts "Rejected values are #{ans}"   
  14.   
  15. range.each do |digit|   
  16.    puts "In Loop #{digit}"   
  17. end  

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:

  1. #!/usr/bin/ruby   
  2. if (('a'..'z') === 'v')   
  3.   puts "v lies in the above range"   
  4. end   
  5.   
  6. if (('50'..'90') === 99)   
  7.   puts "z lies in the above range"   
  8. end  

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:

  1. #!/usr/bin/ruby   
  2.     puts (5..1).to_a   

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:

  1. #!/usr/bin/ruby   
  2.     puts (1..5).to_a.reverse   

Output:

Ruby rangers 4