Array Methods: map, select, reduce
map transforms, select and reject filter, reduce combines, sum adds, min and max find extremes, sort_by orders, group_by and partition split, zip pairs and each_slice chunks.
Example
n = [1, 2, 3, 4, 5, 6]
puts n.map { |x| x * 2 }.inspect
puts n.select(&:even?).inspect, n.reject(&:even?).inspect
puts n.reduce(:+), n.sum, n.minmax.inspect
puts n.partition { |x| x > 3 }.inspect
puts n.each_slice(2).to_a.inspect
puts n.zip(n.rotate).first(2).inspectResult
[2, 4, 6, 8, 10, 12] [2, 4, 6] [1, 3, 5] 21 21 [1, 6] [[4, 5, 6], [1, 2, 3]] [[1, 2], [3, 4], [5, 6]] [[1, 2], [2, 3]]
Exercise
Combine to one value.
n.(:+)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.