Menu
Coddy logo textTech

Select and Reject

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

The select method returns a new array containing only the elements for which the block returns a truthy value. It's how Ruby spells "filter".

numbers = [1, 2, 3, 4, 5, 6]
evens = numbers.select { |n| n.even? }
puts evens.inspect   # [2, 4, 6]

reject is the opposite, it keeps everything for which the block returns false:

odds = numbers.reject { |n| n.even? }
puts odds.inspect    # [1, 3, 5]

Both return a new array; the original is untouched.

The block is just a predicate, anything that evaluates to true or false works:

words = ["hi", "hello", "hey", "yo"]
long  = words.select { |w| w.length >= 3 }
puts long.inspect    # ["hello", "hey"]
challenge icon

Challenge

Beginner

Read a comma-separated list of integers. Print two lines:

  1. The numbers greater than 10 (use select), joined with ,
  2. The numbers not divisible by 3 (use reject), joined with ,

For input 3,7,12,15,20, the output is:

12, 15, 20
7, 20

Cheat sheet

select returns a new array with elements for which the block is truthy (like "filter"):

evens = [1,2,3,4].select { |n| n.even? }  # [2, 4]

reject is the opposite, keeping elements for which the block is falsy:

odds = [1,2,3,4].reject { |n| n.even? }   # [1, 3]

Both return a new array; the original is untouched.

Try it yourself

numbers = gets.chomp.split(",").map(&:to_i)

# TODO: line 1, numbers > 10, joined with ", "
# TODO: line 2, numbers NOT divisible by 3, joined with ", "
quiz iconTest yourself

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

All lessons in Logic & Flow