Ranges (Range) are everywhere: a to z, 0 to 9, and so on. Ruby supports scope and allows us to use scope in different ways:
As the range of a sequence
Scope as a condition
The range used as an interval
6.25.1. As the range of a sequence #
The first and most common use of ranges is to express sequences. A sequence has a starting point, an end point, and a way to generate continuous values in the sequence.
Ruby usage
''..''
and
''...''
the range operator creates these sequences. The two-point form creates a range that contains the specified maximum value, and the three-point form creates a range 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'
Sequence 1. 100 is a The output of the above instance is as follows: Scopes implement methods that allow you to traverse them, and you can check their contents in a number of ways: The output of the above instance is as follows:
Range
object that contains two
Fixnum
a reference to the object. If necessary, you can use the
to_a
method to convert the scope to a list. Try the following example:Example #
#!/usr/bin/ruby$,=","#Array
Value separatorrange1=(1..10).to_arange2=('bar'..'bat').to_aputs"#{range1}"puts"#{range2}"
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
["bar", "bas", "bat"]
Example #
#/ Usr/bin/ruby # - * - coding: UTF-8
-*-#Specify a range of digits=0.9putsdigits. include? (5) Ret=digits. inputs "The minimum value is
#{ret} "ret=digits. maxputs" The maximum value is
#{ret} "ret=digits. subject { | i | i<5} puts" Those that do not meet the conditions are
#{ret} "digits. eachdo | digit | puts" in loop # {digit} "end
True
The minimum value is 0
Maximum value is 9
Those that do not meet the conditions are [5, 6, 7, 8, 9]
In loop 0
In loop 1
In loop 2
In loop 3
In loop 4
In loop 5
In loop 6
In loop 7
In loop 8
In loop 9
6.25.2. Scope as a condition #
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 collection contains words
start
,the last line contains words
end.
:
whilegetsprintif/start/../end/end
The range can be used in The output of the above instance is as follows:
case
statement:Example #
#/ Usr/bin/ruby # - * - coding: UTF-8
-*-Score=70result=casescorewhen0.40 "Bad score" when41.. 60 "
Almost passing" when61.. 70 "Passing score" when71.. 100 "Good score" else "Wrong score" endputsresult
Passing score
6.25.3. The range used as an interval #
The last use of a range is interval detection: to check whether the specified value is within the specified range. Need to use The output of the above instance is as follows:
===
equalityoperator to complete the calculation.Example #
#!/usr/bin/ruby#-*- coding: UTF-8 -*-if((1..10)===5)puts"5 in
(1..10)"endif(('a'..'j')==='c')puts"c in
('a'..'j')"endif(('a'..'j')==='z')puts"z in ('a'..'j')"end
5 in (1..10)
c in ('a'..'j')