Ruby Range

Ranges are everywhere: a to z, 0 to 9, and so on. Ruby supports ranges and allows us to use ranges in different ways:

  • Ranges as Sequences
  • Ranges as Conditions
  • Ranges as Intervals

Ranges as Sequences

The first and most common use of ranges is to express sequences. Sequences have a start point, an end point, and a way to produce successive values in the sequence.

Ruby uses''..''and''...''range operators to create these sequences. The two-dot form creates a range that includes the specified highest value, and the three-dot 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 aRangeobject that contains twoFixnumreferences to objects. If necessary, you can useto_amethod to convert the range to a list. Try the following example:

Example

#!/usr/bin/ruby $, =", " #Array value separator range1 = (1..10).to_a range2 = ('bar'..'bat').to_a puts "#{range1}" puts "#{range2}"

Try it »

The output of the above example is:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
["bar", "bas", "bat"]

Ranges implement methods that let you iterate over them and check their contents in various ways:

Example

#!/usr/bin/ruby # -*- coding: UTF-8 -*- #Specified range digits = 0..9 puts digits.include?(5) ret = digits.min puts "The minimum value is #{ret}" ret = digits.max puts "The maximum value is #{ret}" ret = digits.reject {|i| i < 5 } puts "The ones that do not meet the condition are #{ret}" digits.each do |digit| puts "In the loop #{digit}" end

Try it »

Running the above example produces:

true
最小值为 0
最大值为 9
不符合条件的有 [5, 6, 7, 8, 9]
在循环中 0
在循环中 1
在循环中 2
在循环中 3
在循环中 4
在循环中 5
在循环中 6
在循环中 7
在循环中 8
在循环中 9

Ranges as Conditions

Ranges can also be used as conditional expressions. For example, the following code snippet prints lines from standard input, where the first line of each set contains the wordstart, and the last line contains the wordend.:

while gets print if /start/../end/ end

Ranges can be used in case statements:

Example

#!/usr/bin/ruby # -*- coding: UTF-8 -*- score = 70 result = case score when 0..40 "Poor score" when 41..60 "Almost passing" when 61..70 "Passing score" when 71..100 "Good score" else "Invalid score" end puts result

Try it »

The above example outputs:

Passing score

Ranges as Intervals

The last use of ranges is interval detection: checking whether a specified value falls within a specified range. This requires the === equality operator to perform the calculation.

Example

#!/usr/bin/ruby # -*- coding: UTF-8 -*- if ((1..10) === 5) puts "5 in (1..10)" end if (('a'..'j') === 'c') puts "c in ('a'..'j')" end if (('a'..'j') === 'z') puts "z in ('a'..'j')" end

Try it »

The above example outputs:

5 在 (1..10)
c 在 ('a'..'j')
Other Extensions