I don’t use map and reduce in Ruby a lot, but when I do I always like to have some samples to look at to refresh my memory. These are those examples.

map

Map works on an Enumerable, invokes a block on each element in the enumerable, and returns an array of the output.

[1, 2, 3, 4, 5].map{|i| i+1 } #=> [2, 3, 4, 5, 6]
[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]
["chris", "kevin", "jeff"].map { |n| n.capitalize } #=> ["Chris", "Kevin", "Jeff"]

reduce

Reduce combines all elements of an enumerable through a given operation or block, optionally with an initial starting value.

[1, 2, 3].reduce(:+) #=> 6
[2, 3, 4].reduce(:*) #=> 24
[1, 2, 3].reduce(10, :+) #=> 16
["hi", "my", "friend"].reduce { |phrase, word| "#{phrase} #{word}" } #=> "hi my friend"

Combining map and reduce

Implementing lowecase rot13 with Map and Reduce.

"a".ord == 97 and "z".ord == 122

s = "abcdefghijklmnopqrstuvwxyz"
s.downcase.chars.map{ |c|
	ord = c.ord
	if ord >= 97 and ord <= 122
		ord += 13
		ord -= 26 if ord > 122
	end
	ord.chr
}.reduce('', :+)