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
BeginnerRead a comma-separated list of integers. Print two lines:
- The numbers greater than
10(useselect), joined with, - The numbers not divisible by
3(usereject), joined with,
For input 3,7,12,15,20, the output is:
12, 15, 20
7, 20Cheat 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 ", "
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