each, map, select, reject
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: