Range operators in ruby are used to extract a sequence. Sequences have an initial point and end point by which we can generate consecutive values in the sequence. The values of a range may be objects, numbers, characters or strings.
 
There are two types of range operators:
1. Inclusive range operator that is two-dot (..)
2. Exclusive operator that is three-dot operator (...)
 
Inclusive range operator that is two-dot (..) operator: This operator contains both the start and end values in the range.
Example1: 
2.2.1 :006 >   (1..5).each do |v| 
2.2.1 :007 >     puts v 
2.2.1 :008?>   end 
Output: 
1 
2 
3 
4 
5 
Start point: 1 & End point: 5 
 
Example2: 
2.2.1 :003 > (1..5).to_a 
 => [1, 2, 3, 4, 5] 
Output: [1, 2, 3, 4, 5]
 
Example3: 
2.2.1 :010 > ('A'..'E').to_a 
 => ["A", "B", "C", "D", "E"] 
Output: ["A", "B", "C", "D", "E"] 
 
Exclusive operator that is three-dot operator (...): This operator excludes end point in the range.
Example1: 
2.2.1 :006 >   (1..5).each do |v| 
2.2.1 :007 >     puts v 
2.2.1 :008?>   end 
Output: 
1 
2 
3 
4 
Start point: 1 & End point: 4 
Example2: 
2.2.1 :003 > (1..5).to_a 
 => [1, 2, 3, 4, 5]
 
Output: [1, 2, 3, 4] 
Example3: 
2.2.1 :014 > ('AA'...'AH').to_a 
 => ["AA", "AB", "AC", "AD", "AE", "AF", "AG"] 
Output: ["AA", "AB", "AC", "AD", "AE", "AF", "AG"] 
Start point: ' AA' & End point: 'AG' # excluded 'AH' from output array 
 
                       
                    
0 Comment(s)