Explain the concept of range in Ruby and the concept of Ruby range.
The scope is everywhere: From January 1, January to January 1, December, from December 9 to December 9, 50 to 67 rows, and so on. Ruby supports a range and allows us to use multiple methods:
- As sequence range
- As condition range
- Range
As sequence range:
First, it may be the most natural use range to express the sequence. A sequence has a starting point, and a method for producing an end point and a continuous value in the sequence.
Ruby creates ''...'' and ''...''. These sequences are used by operators in the range. The two vertices form an inclusive range, while the three vertices form a range, excluding the specified high 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 reference of an object with two Fixnum as a Range object. If necessary, you can use the to_a Method for a series of lists. Try the following example:
#!/usr/bin/ruby
$, =", " # Array value separator
range1 = (1..10).to_a
range2 = ('bar'..'bat').to_a
puts "#{range1}"
puts "#{range2}"
This produces the following results:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
bar, bas, bat
Range implementation methods can iterate between them and test their content in different ways:
#!/usr/bin/ruby
# Assume a range
digits = 0..9
puts digits.include?(5)
ret = digits.min
puts "Min value is #{ret}"
ret = digits.max
puts "Max value is #{ret}"
ret = digits.reject {|i| i < 5 }
puts "Rejected values are #{ret}"
digits.each do |digit|
puts "In Loop #{digit}"
end
This produces the following results:
true
Min value is 0
Max value is 9
Rejected values 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
Scope as a condition:
The range can also be used as a conditional expression. For example, the following code snippet prints a set of lines from the standard input. The first line in each group contains the last line of the word starting and ending:
while gets
print if /start/../end/
end
The range can use the case statement:
#!/usr/bin/ruby
score = 70
result = case score
when 0..40: "Fail"
when 41..60: "Pass"
when 61..70: "Pass with Merit"
when 71..100: "Pass with Distinction"
else "Invalid Score"
end
puts result
This produces the following results:
Pass with Merit
Range:
The range of the last full range is the interval test: whether a value falls within the interval, which is equal when = is used.
#!/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
This produces the following results:
5 lies in (1..10)
c lies in ('a'..'j')