Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Ruby Range


May 12, 2021 Ruby


Table of contents


Ruby Range

Range is everywhere: January to December, 0 to 9, and so on. Ruby supports scope and allows us to use scope in different ways:

  • As the range of the sequence
  • The range as a condition
  • As the range of intervals

As the range of the sequence

The first and most common use of a range is to express sequences. A sequence has a starting point, an end point, and a way to produce consecutive values in the sequence.

Ruby ''..'' ''...'' range operators. Two-point form creates a range that contains the specified highest value, and three-point form creates a range that does not contain the specified highest value.

(1..5)        #==> 1, 2, 3, 4, 5
(1...5)       #==> 1, 2, 3, 4
('a'..'d')    #==> 'a', 'b', 'c', 'd'

Sequence 1..100 is a Range object that contains references to two Fixnum objects. I f you want, you can to_a to convert the 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}"
Try it out . . .


This results in the following:

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

Scope implements methods that allow you to traverse them, and you can examine their contents in a number of ways:

#!/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

Try it out . . .


This results in the following:

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

The range as a condition

The range can also be used as a conditional expression. F or example, the following snippets print 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

Scopes can be used in case statements:

#!/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

Try it out . . .


This results in the following:

及格分数

As the range of intervals

The last use of a range is the interval test: to check that some values fall in the interval represented by the range. This is done using the equal operator

#!/usr/bin/ruby

if ((1..10) === 5)
  puts "5 lies in (1..10)"
end

if (('a'..'j') === 'c')
  puts "c lies in ('a'..'j')"
end

if (('a'..'j') === 'z')
  puts "z lies in ('a'..'j')"
end
Try it out . . .


This results in the following:

5 lies in (1..10)
c lies in ('a'..'j')