Ranges
A range is a shortcut for a run of values, like one to five without writing them all. Two dots include the last number and three dots leave it out.
In this page:
Syntax
inclusive = (start..finish)
exclusive = (start...finish)
range.to_a
range.include?(value)
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
1..5and expecting the last number to be excluded, when..includes it and...excludes it. - Calling
(5..1).to_aand expecting[5, 4, 3, 2, 1], when a backward range is empty; use5.downto(1). - Writing
1..5.eachwithout parentheses, which callseachon5; write(1..5).each.
Chapter Summary
- Arrays are created and changed with methods such as
push,pop,shift, andunshift. each,map,select, andrejectiterate and transform elements.flatten,zip, other array methods, and ranges help work with collections.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: