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

each, map, select, reject

each, map, select, and reject go through every item in a list: each does something with it, map transforms it, select keeps the good ones, and reject throws out the bad ones. It is like a teacher handling each paper in the pile.
Syntax
ruby
array.each { |item| # side effect }
result = array.map { |item| expression }
result = array.select { |item| condition }
result = array.reject { |item| condition }

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using each and expecting a new array, when it returns the original array; use map to build a new one.
  2. Using map with a block that only prints, so the result array is full of nil.
  3. Confusing select and reject, when select keeps items where the block is true and reject removes them.
🔒

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.