Difference between map, select, collect, inject, detect and each in ruby
Everything in ruby is a object. Ruby supports lots of methods where one task can be done using multiple methods or ways. Array is an object for which map
, each
, select
, collect
, inject
, detect
are ruby methods for a object Array. Let’s understand all these methods thoroughly.
1) Map
Map takes the enumerable object and a block, evaluates the block for each element and then return a new array with the calculated values.
[1,2,3,4,5,6,7,8,9,10].map{ |e| e * 5 } # => [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
If you are try to use map to select any specific values like where e <= 3 then it will evaluate each element and will output only the result which will be either true or false
[1,2,3,4,5,6,7,8,9,10].map{ |e| e <= 3 } # => [true, true, true, false, false, false, false, false, false, false]
2) Select
Select evaluates the block with each element for which the block returns true.
[1,2,3,4,5,6,7,8,9,10].select{ |e| e > 5 } # => [6 ,7, 8, 9, 10]
and also, select would return a element for which the statement is true.
[1,2,3,4,5,6,7,8,9,10].select{ |e| e * 3 } # => [1,2,3,4,5,6,7,8,9,10]
3) Collect
Collect is similar to Map which takes the enumerable object and a block, evaluates the block for each element and then return a new array with the calculated values.
[1,2,3,4,5,6,7,8,9,10].collect{ |e| e * 5 } # => [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
If you are try to use collect to select any specific values like where n <= 3 then it will evaluate each element and will output only the result which will be either true or false
[1,2,3,4,5,6,7,8,9,10].collect{ |e| e <= 3 } # => [true, true, true, false, false, false, false, false, false, false]
4) Each
Each will evaluate the block with each array and will return the original array not the calculated one.
[1,2,3,4,5,6,7,8,9,10].each{ |e| print "#{e}!" e * 3 } 1!2!3!4!5!6!7!8!9!10! => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If you are try to use each to select any specific values like where e <= 3 then it will evaluate each element but returns the original array
[1,2,3,4,5,6,7,8,9,10].each{ |e| e <= 3 } # => [1,2,3,4,5,6,7,8,9,10]
5) 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.
If you do not explicitly specify an initial value for accumlator, then uses the first element of collection is used as the initial value of accumulator.
[1,2,3,4,5,6,7,8,9,10].inject{ |sum, e| sum += e } # => 55 [1,2,3,4,5,6,7,8,9,10].inject(15){ |sum, e| sum += e } # => 70
6) Detect
Detect is equal to select.first
, as simple as that. Detect evaluates the block with each element for which the block returns true, but gives back only the first element as the result.
[1,2,3,4,5,6,7,8,9,10].detect{ |e| e > 5 } # => 6
and also, detect would return the first element for which the statement is true.
[1,2,3,4,5,6,7,8,9,10].detect{ |e| e * 3 } # => 1