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.
In this page:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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
- Using
eachand expecting a new array, when it returns the original array; usemapto build a new one. - Using
mapwith a block that only prints, so the result array is full ofnil. - Confusing
selectandreject, whenselectkeeps items where the block is true andrejectremoves them.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: