Ruby Range
Ranges are everywhere: a to z, 0 to 9, etc. Ruby supports ranges and allows us to use ranges in different ways:
Range as a sequence
Range as a condition
Range as interval
Range as sequence
The first and most common use of range is to express sequences . A sequence has a starting point, an ending point, and a way of producing consecutive values in the sequence.
Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-point form creates a range that includes the specified highest value, and the three-point form creates a range that does not include the specified highest value.
(1..5) #==> 1, 2, 3, 4, 5 (1...5) #==> 1, 2, 3, 4 ('a'..'d') #==> 'a', 'b', 'c', 'd'
The sequence 1..100 is a Range object that contains references to two Fixnum objects. If needed, you can convert a range to a list using the to_a method. Try the following example:
#!/usr/bin/ruby $, =", " # Array 值分隔符 range1 = (1..10).to_a range2 = ('bar'..'bat').to_a puts "#{range1}" puts "#{range2}"
The output of the above example is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ["bar", "bas", "bat"]
Ranges implement methods that allow you to traverse them. You can pass multiple There are three ways to check their contents:
#!/usr/bin/ruby # -*- coding: UTF-8 -*- # 指定范围 digits = 0..9 puts digits.include?(5) ret = digits.min puts "最小值为 #{ret}" ret = digits.max puts "最大值为 #{ret}" ret = digits.reject {|i| i < 5 } puts "不符合条件的有 #{ret}" digits.each do |digit| puts "在循环中 #{digit}" end
The output result of the above example is:
true 最小值为 0 最大值为 9 不符合条件的有 [5, 6, 7, 8, 9] 在循环中 0 在循环中 1 在循环中 2 在循环中 3 在循环中 4 在循环中 5 在循环中 6 在循环中 7 在循环中 8 在循环中 9
The range as the condition
The range can also be Used as conditional expression. For example, the following code snippet prints lines from standard input where the first line of each collection contains the word start and the last line contains the word end.:
while gets print if /start/../end/ end
The range can be used in the case statement:
#!/usr/bin/ruby # -*- coding: UTF-8 -*- score = 70 result = case score when 0..40 "糟糕的分数" when 41..60 "快要及格" when 61..70 "及格分数" when 71..100 "良好分数" else "错误的分数" end puts result
The output result of the above example is:
及格分数
As the range of the interval
The range is The final use is interval detection: checking whether a specified value is within a specified range. The === equality operator is required to complete the calculation.
#!/usr/bin/ruby # -*- coding: UTF-8 -*- if ((1..10) === 5) puts "5 在 (1..10)" end if (('a'..'j') === 'c') puts "c 在 ('a'..'j')" end if (('a'..'j') === 'z') puts "z 在 ('a'..'j')" end
The output result of the above example is:
5 在 (1..10) c 在 ('a'..'j')