Ranges
In this page:
Ranges
A range, written as 1..5 (inclusive) or 1...5 (exclusive of the end), represents a sequence of values and can be converted to an array with .to_a. Ranges are commonly used for iteration ((1..5).each) and for slicing arrays or strings. They're lazily evaluated, so (1..Float::INFINITY) doesn't try to build an infinite array right away.
Warning: 1...5 (three dots) excludes the final value, while 1..5 (two dots) includes it -- easy to confuse at a glance.
Example: Ranges
inclusive = (1..5).to_a
exclusive = (1...5).to_a
puts inclusive.inspect
puts exclusive.inspect
(1..3).each { |n| puts "Number: #{n}" }
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: