What is a Range?
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 6 of 56.
You've already used ranges with for loops and array slicing. But a range is a real Ruby object, not just syntax, it has its own methods.
Create one with .. (two dots, inclusive) or ... (three dots, exclusive of the end value):
inclusive = 1..5 # 1, 2, 3, 4, 5
exclusive = 1...5 # 1, 2, 3, 4Convert a range to an array with to_a to see exactly what it covers:
puts (1..5).to_a.inspect # [1, 2, 3, 4, 5]
puts (1...5).to_a.inspect # [1, 2, 3, 4]Ranges aren't only for numbers. They work with anything that has an order, including letters:
puts ("a".."e").to_a.inspect # ["a", "b", "c", "d", "e"]Challenge
BeginnerRead two integers (two lines of input): a start and an end_value. Print three lines:
- The inclusive range
start..end_valueas an array (useinspect) - The exclusive range
start...end_valueas an array - The size of the inclusive range
For input 1 then 5, the output is:
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
5Cheat sheet
Ranges in Ruby use .. (inclusive) or ... (exclusive of end):
inclusive = 1..5 # 1, 2, 3, 4, 5
exclusive = 1...5 # 1, 2, 3, 4Convert a range to an array with to_a:
puts (1..5).to_a.inspect # [1, 2, 3, 4, 5]
puts (1...5).to_a.inspect # [1, 2, 3, 4]Ranges also work with letters:
puts ("a".."e").to_a.inspect # ["a", "b", "c", "d", "e"]Try it yourself
start = gets.to_i
end_value = gets.to_i
# TODO: print the inclusive range, exclusive range, and inclusive size
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier