Introduction
Range operators help you create a list of values between a start and an end point easily.
Range operators help you create a list of values between a start and an end point easily.
start..end # Includes end value start...end # Excludes end value
The .. operator creates a range including the last value.
The ... operator creates a range excluding the last value.
1..5 # This creates a range including 1, 2, 3, 4, 5
1...5 # This creates a range including 1, 2, 3, 4 but not 5
'a'..'e' # This creates a range including 'a', 'b', 'c', 'd', 'e'
'a'...'e' # This creates a range including 'a', 'b', 'c', 'd' but not 'e'
This program shows how the two range operators work by printing numbers from 1 to 5 with and without including 5.
puts "Using .. operator:" (1..5).each { |num| print "#{num} " } puts "\nUsing ... operator:" (1...5).each { |num| print "#{num} " }
Ranges can be used with numbers, letters, and other objects that can be compared.
Ranges are often used in loops and conditions to simplify code.
The .. operator creates a range including the end value.
The ... operator creates a range excluding the end value.
Ranges make it easy to work with sequences of values.
.. and ...?.. operator.. operator creates a range that includes the last value in the sequence.... operator... operator creates a range that excludes the last value, stopping just before it... includes the end value, ... excludes the end value -> Option A.., exclusion = ... [OK]... operator excludes the end value, so 1...5 means 1, 2, 3, 4.1..5 includes 5, (1..5).exclude_end? is a method call, not range creation, and 1-5 is subtraction.... [OK]puts (1..3).to_a.inspect
puts (1...3).to_a.inspect
1..3 includes 3, so (1..3).to_a is [1, 2, 3].1...3 excludes 3, so (1...3).to_a is [1, 2].for i in 1..5
puts i
end
1..5 includes 5, so the loop prints 1 through 5.... operator: 1...5 which stops before 5.... to exclude 5 -> Option C... [OK]n. Which range operator should you use inside the method to achieve this?n.1...n creates a range that excludes n, exactly what is needed.1..n includes n, 1...(n+1) includes n, 1...n-1 excludes n-1 too, which is incorrect.1...n to exclude n -> Option APass the test and this pattern moves unknown