Range objects in Ruby Learning notes _ruby topics

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.