Menu
Coddy logo textTech

Range Methods

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 7 of 56.

Ranges come with handy methods that save you from writing loops by hand.

include? checks whether a value falls inside the range:

range = 1..10
puts range.include?(5)   # true
puts range.include?(11)  # false

min, max, and size work directly on ranges:

puts (1..10).min   # 1
puts (1..10).max   # 10
puts (1..10).size  # 10

step iterates over the range jumping by a fixed amount, useful when you don't want every value:

(0..10).step(2) do |n|
  puts n
end
# 0, 2, 4, 6, 8, 10

And each works just like on arrays:

(1..3).each { |n| puts n * n }
# 1
# 4
# 9
challenge icon

Challenge

Easy

You're given an inclusive range and a list of guesses. Score the guesses and summarise the range.

Read two lines:

  1. Two integers separated by a space: start and end_value
  2. A comma-separated list of integer guesses

Using the range start..end_value, print:

  1. Hit: <n>, where n is how many guesses fall inside the range (use include?)
  2. Span: <n>, where n is the range's size
  3. Multiples of 3 sum: <n>, where n is the sum of every multiple of 3 in the range (use step starting from the first multiple of 3 at or after start)

For input 1 10 on the first line and 3,5,11,7,-2 on the second, the output is:

Hit: 3
Span: 10
Multiples of 3 sum: 18

(Hits: 3, 5, 7. Multiples of 3 in 1..10: 3+6+9 = 18.)

Cheat sheet

Useful Range methods:

range = 1..10
range.include?(5)  # true
range.min          # 1
range.max          # 10
range.size         # 10

step iterates jumping by a fixed amount:

(0..10).step(2) { |n| puts n }
# 0, 2, 4, 6, 8, 10

each works just like on arrays:

(1..3).each { |n| puts n * n }

Try it yourself

start, end_value = gets.chomp.split.map(&:to_i)
guesses = gets.chomp.split(",").map(&:to_i)

# TODO: Hit count via include?, Span via size, sum of multiples of 3 via step
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow