HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
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:
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'' /en '' and '' /en. ''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/en5) #==> 1, 2, 3, 4, 5 (1/en.5) #==> 1, 2, 3, 4 ('a'/en'd') #==> 'a', 'b', 'c', 'd'
1/en100 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/en10).to_a range2 = ('bar'/en'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/en9 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
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//en/end/ end
Range can be used in case statement:
#!/usr/bin/ruby # -*- coding: UTF-8 -*- score = 70 result = case score when 0/en40 "糟糕的分数" when 41/en60 "快要及格" when 61/en70 "及格分数" when 71/en100 "良好分数" else "错误的分数" end puts result
Run the above example output is:
及格分数
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/en10) === 5) puts "5 在 (1/en10)" end if (('a'/en'j') === 'c') puts "c 在 ('a'/en'j')" end if (('a'/en'j') === 'z') puts "z 在 ('a'/en'j')" end
Run the above example output is:
5 在 (1/en10) c 在 ('a'/en'j')