The range is everywhere: January to December, 0 to 9, 50 to 67 lines, and so on. Ruby supports scopes and allows us to use scopes in multiple ways:
As sequence range
As condition range
As interval range
As a sequence range:
First, and perhaps the most natural use of scope is to express sequences. A sequence has a starting point, an end point, and continuous values in the sequence to produce.
Ruby creates operators in the range `` .. '' and `` ... '' to use these sequences. The two-point form creates an inclusive range, while the three-point form creates a range excluding the specified high value.
(1..5) # ==> 1, 2, 3, 4, 5
(1 ... 5) # ==> 1, 2, 3, 4
('a' .. 'd') # ==> 'a', 'b', 'c', 'd'
The sequence 1..100 as a Range object contains references to two Fixnum objects. If necessary, you can use a to_a method for a series of lists. Try the following example:
#! / usr / bin / ruby
$, = "," # Array value separator
range1 = (1..10) .to_a
range2 = ('bar' .. 'bat'). to_a
puts "# {range1}"
puts "# {range2}"
This will produce the following results:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
bar, bas, bat
Scope implementation methods that iterate between them and test their content in various ways:
#! / usr / bin / ruby
# Assume a range
digits = 0..9
puts digits.include? (5)
ret = digits.min
puts "Min value is # {ret}"
ret = digits.max
puts "Max value is # {ret}"
ret = digits.reject {| i | i <5}
puts "Rejected values are # {ret}"
digits.each do | digit |
puts "In Loop # {digit}"
end
This will produce the following results:
true
Min value is 0
Max value is 9
Rejected values are 5, 6, 7, 8, 9
In Loop 0
In Loop 1
In Loop 2
In Loop 3
In Loop 4
In Loop 5
In Loop 6
In Loop 7
In Loop 8
In Loop 9
Range as condition:
Ranges can also be used as conditional expressions. For example, the following code snippet prints a set of lines from standard input, with the first line in each group containing the last line of words beginning and ending:
while gets
print if /start/../end/
end
Scopes can use case statements:
#! / usr / bin / ruby
score = 70
result = case score
when 0..40: "Fail"
when 41..60: "Pass"
when 61..70: "Pass with Merit"
when 71..100: "Pass with Distinction"
else "Invalid Score"
end
puts result
This will produce the following results:
Pass with Merit
Interval range:
The last all-around range to use is for interval testing: if any value falls within the interval's time interval, this is an equal operation using ===.
#! / usr / bin / ruby
if ((1..10) === 5)
puts "5 lies in (1..10)"
end
if (('a' .. 'j') === 'c')
puts "c lies in ('a' .. 'j')"
end
if (('a' .. 'j') === 'z')
puts "z lies in ('a' .. 'j')"
end
This will produce the following results:
5 lies in (1..10)
c lies in ('a' .. 'j')