RbRuby
IntermediateLesson 9 of 16

Enumerable: map, select, reduce & Co. – Ruby

Processing data without loops – with the methods that arrays, hashes and ranges share.

The Enumerable module provides dozens of methods for everything that knows each. The most important ones: map (transform), select/reject (filter), reduce (combine), find, partition, each_slice.

zahlen = [1, 2, 3, 4, 5, 6]
puts zahlen.map { |x| x * 2 }.inspect        # [2, 4, 6, 8, 10, 12]
puts zahlen.select(&:even?).inspect          # [2, 4, 6]
puts zahlen.reject(&:even?).inspect          # [1, 3, 5]
puts zahlen.reduce(:+)                       # 21
puts zahlen.inject(1) { |a, b| a * b }       # 720
puts zahlen.sum, zahlen.min, zahlen.max      # 21, 1, 6
puts zahlen.find { |x| x > 3 }               # 4
puts zahlen.count(&:odd?)                    # 3
puts zahlen.take_while { |x| x < 4 }.inspect # [1, 2, 3]
puts zahlen.each_slice(2).to_a.inspect       # [[1, 2], [3, 4], [5, 6]]
puts zahlen.each_cons(2).first(2).inspect    # [[1, 2], [2, 3]]
puts zahlen.partition(&:even?).inspect       # [[2, 4, 6], [1, 3, 5]]
puts zahlen.any? { |x| x > 5 }, zahlen.all?(&:positive?), zahlen.none?(&:zero?)

For grouping and counting there are group_by, tally, sort_by, max_by. With filter_map (Ruby 2.7) you filter and transform in one step.

woerter = %w[apfel birne kiwi apfel birne apfel]
puts woerter.tally.max_by { |_, n| n }.inspect      # ["apfel", 3]
woerter.group_by(&:size).each do |laenge, ws|
  puts "#{laenge}: #{ws.uniq.inspect}"              # 5: ["apfel", "birne"] / 4: ["kiwi"]
end
puts woerter.sort_by { |w| [-w.size, w] }.uniq.inspect   # ["apfel", "birne", "kiwi"]
puts [1, 2].zip([:a, :b]).inspect                   # [[1, :a], [2, :b]]

bestellungen = [
  { artikel: "Coffee", preis: 4.5, menge: 2 },
  { artikel: "Tea",    preis: 3.0, menge: 1 },
  { artikel: "Cookie",   preis: 1.2, menge: 5 }
]
puts bestellungen.sum { |b| b[:preis] * b[:menge] }             # 18.0
puts bestellungen.max_by { |b| b[:preis] }[:artikel]            # Coffee
puts bestellungen.filter_map { |b| b[:artikel] if b[:menge] > 1 }.inspect   # ["Coffee", "Cookie"]
puts bestellungen.flat_map { |b| [b[:artikel]] * b[:menge] }.size           # 8

With lazy, chains are only evaluated on demand – which even makes infinite sequences possible:

ergebnis = (1..Float::INFINITY).lazy.select(&:even?).map { |x| x * x }.first(3)
puts ergebnis.inspect      # [4, 16, 36]
Warningeach returns the original, not the results of the block. If you want to transform, you need map. And map with puts in the block returns an array full of nil.
TipYour own classes get all these methods for free: include Enumerable and define an each method (see the lesson on modules).