MΓ³dulo 02 Β· Collections & Blocks β LecciΓ³n 4 de 6 Β· ~9 min
Transform: map & select
map β transform every item into something new
each just runs a block; it hands back the original collection untouched. map runs a block too, but collects what the block RETURNS into a brand-new array β this is a transform, same idea as Swift/JS's .map, just with a Ruby block instead of an arrow function:
names = ["ana", "ben", "cleo"]
upcased = names.map { |n| n.upcase }
# ["ANA", "BEN", "CLEO"]map also shines on an array of hashes β pull one field out of every element:
bookings = [{ dog: "Mochi", price_cents: 2500 }, { dog: "Rex", price_cents: 3000 }]
dogs = bookings.map { |b| b[:dog] }
# ["Mochi", "Rex"]