← Back to Ruby Course | Chapter 4: Arrays | Lesson 3 of 7

each, map, select, reject

each, map, select, reject

each iterates over an array running a block for its side effects, without building a new array. map transforms every element and returns a new array of results. select keeps only elements where the block returns true, and reject keeps only elements where it returns false -- the exact opposite of select. These four are the core of Ruby's enumerable-based, block-driven style.

Note: Use map when you want a transformed array back; use each when you only care about side effects like printing.

Example: each, map, select, reject

markup
numbers = [1, 2, 3, 4, 5]

numbers.each { |n| puts "Value: #{n}" }

doubled = numbers.map { |n| n * 2 }
puts doubled.inspect

evens = numbers.select { |n| n.even? }
odds = numbers.reject { |n| n.even? }

puts evens.inspect
puts odds.inspect
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.