Ruby can express Ranges as a sequences those sequences have the starting point and ending point and which produce some successive values. The sequence can be created by using the
".." and
"..." range operators in which 2 dots forms an inclusive range and 3 dots form excluded range which specified the peaks value. The snippet below demonstrates range from starting point to ending point as shown below.
[ruby]
(1..5) #==> 1, 2, 3, 4, 5
(1...5) #==> 1, 2, 3, 4
('a'..'d') #==> 'a', 'b', 'c', 'd'
[/ruby]
User can change the range to a list with to_a method. The code below demonstrates to convert to 1..1000 sequence to two
Fixnum objects as shown below.
[ruby]
$, =", " # Array value separator
range1 = (1..10).to_a
range2 = ('bar'..'bat').to_a
puts "#{range1}"
puts "#{range2}"
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.
Ranges implements some methods which iterate over them and test the contents in a different ways as shown in below code.
[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
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.