Latest web development tutorials

Ruby Range (Range)

Range (Range) is everywhere: a to z, 0 through 9, and so on. Ruby support range, and allows us to use a range of different ways:

  • As the range of sequence
  • As the range of conditions
  • As the range of interval

As the range of sequence

The first and most common use of the range is expressed sequences. Sequence has a starting point and an end point in a sequence to produce a continuous value.

Ruby uses'' .. '' and '' ... ''range operator to create these sequences. Two forms create a range that contains the highest value of the specified three-point range to create a form that does not contain the specified maximum value.

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

1..100 sequence is aRangeobject containing twoFixnumobject. If necessary, you can use the method toto_arange into a list. Try the following examples:

#!/usr/bin/ruby

$, =", "   # Array 值分隔符
range1 = (1..10).to_a
range2 = ('bar'..'bat').to_a

puts "#{range1}"
puts "#{range2}"

Run the above example output is:

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

So that you can achieve a range of traverse their methods, you can check their contents in several 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

Run the above example output is:

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

As the range of conditions

Ranges also be used as a conditional expression. For example, the following code fragment print from standard input line, wherein each of the first rows of the collection contains the wordstart,the last line contains the wordend.:

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

Range can be used in 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

Run the above example output is:

及格分数

As the range of interval

Finally, a use pattern interval detection: Check the specified value is within the specified range. === You need to use the equality operator 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

Run the above example output is:

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