Ruby map, each, collect, inject, reject, select quick reference

Ruby map, each, collect, inject, reject, select quick reference

Last updated:
Table of Contents

map

Performs an action on each array element. The original array is not modified. Returns the modified array.

[1,2,3,4,5,6,7,8,9,10].map{|e| e*3 }
# returns [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

each

Executes an action using as parameter each element of the array. Returns the unmodified array.

[1,2,3,4,5,6,7,8,9,10].each{|e| print e.to_s+"!" }
# prints "1!2!3!4!5!6!7!8!9!10!"
# returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

collect

Alias for map

inject

Takes an accumulator (sum) and changes it as many times as there are elements in the array. Returns the final value of the accumulator.

[1,2,3,4,5,6,7,8,9,10].inject{|sum,e| sum += e }
# returns 55

You can also specify an initial value as parameter before the block.

["bar","baz","quux"].inject("foo") {|acc,elem| acc + "!!" + elem }
# returns "foo!!bar!!baz!!quux" 

reduce

Alias for inject

select

Runs an expression for each array element and, if it is true, that element gets added to the output which is returned. This is called filter in other languages.

[1,2,3,4,5,6,7,8,9,10].select{|el| el%2 == 0 }
# returns [2,4,6,8,10]

find

Take an expression and returns the first element for which the expression returns true:

[1,2,3,4,5,6,7,8,9,10].find{|el| el / 2 == 2 }
# returns 4

detect

Alias for find

reject

The opposite of select: runs an expression for each array element and includes that element in the output if the expression is false

[1,2,3,4,5,6,7,8,9,10].reject{|e| e==2 || e==8 }
# returns [1, 3, 4, 5, 6, 7, 9, 10]

Dialogue & Discussion