Range is a class of range objects. The range operator ".." or "..." can be used when defining. Starting point and ending point, the range is composed of a sequence of regular and regular element objects. Any sequence and regular set of objects can be defined with Range objects, such as numbers, letters, strings, and even time
1. Definition of Range object
The code is as follows:
r1 = 1..5 #Define the range object r1, including elements 1,2,3,4,5
r2 = Range.new (1,5) #equivalent to 1..5
r3 = 1 ... 5 #Defining the range object r3, including elements 2, 3, 4
r4 = Range.new (1,5, true) #equivalent to 1 ... 5
2. The magical use of Range objects
Copy the code The code is as follows:
r = rand * 100
rf = format ('%. 2f', r)
case r
when 90..100
puts "Score: # {rf} Achievement: Excellent"
when 70..90
puts "Score: # {rf} Achievement: Good"
when 50..70
puts "Score: # {rf} Score: Pass"
else
puts "Score: # {rf} Achievement: Failed"
end
Usually we traverse a time is a very troublesome process, but with Range, it will be very simple, as the following example code:
The code is as follows:
#Traverse every day from 2013-01-01 to 2013-02-28, the object is Date
begin_date = Date.parse '2013-01-01'
end_date = Date.parse '2013-02-28'
r1 = begin_date .. end_date
r1.each {| date | puts date}
# Traverse all strings of abc-xyz
r2 = 'abc' .. 'xyz'
r2.each {| str | puts str}
#Determine whether an element is within a certain range
r3 = 'a' .. 'z'
puts r3 === 'A' #false
puts r3.include? 'k' #true
puts r3.min #a
puts r3.max #z
puts r3.first (3) # a, b, c
puts r3.last (4) # w, x, y, z