This post is not related to rails part but the RUBY part.
To iterate over an array we generally use collect, select, map and each. As I am beginner I never actually thought what is the difference and I kept using EACH for every loop iteration. However, recently I researched a bit more about these loops and thought to share it . It might help some one I guess :)
1) Map
Map takes the enumerable object and a block like this [1,2,3].map { |n| n*2 } and evaluates the block for each element and then return a new array with the calculated values.
so the outcome of [1,2,3].map { |n| n*2 } will be [2,4,6]
If you are try to use map to select any specific values like where n >2 then it will evaluate each element and will output only the result which will be either true or false
so the outcome of [1,2,3].map { |n| n>2 } will be [false, false, true]
2) Collect
Collect is similar to Map which takes the enumerable object and a block like this [1,2,3].collect { |n| n*2 } and evaluates the block for each element and then return a new array with the calculated values.
so the outcome [1,2,3].collect{ |n| n*2 } of will be [2,4,6]
If you are try to use collect to select any specific values like where n >2 then it will evaluate each element and will output only the result which will be either true or false
so the outcome of [1,2,3].collect { |n| n>2 } will be [false, false, true]
3) Select
Select evaluates the block with each element for which the block returns true.
so the outcome of [1,2,3].select { |n| n*2 } will be [1,2,3]
If you are try to use select to get any specific values like where n >2 then it will evaluate each element but returns the array that meets the condition
so the outcome of [1,2,3].select{ |n| n>2 } will be [3]
4) Each
Each will evaluate the block with each array and will return the original array not the calculated one.
so the outcome of [1,2,3].each{ |n| n*2 } will be [1,2,3]
If you are try to use each to select any specific values like where n >2 then it will evaluate each element but returns the original array
so the outcome of [1,2,3].each { |n| n>2 } will be [1,2,3]
Thanks! It helped me!
ReplyDeleteJust want to add that Map and Collect are the same method (aliases).
Hey Thanks for the tip :) :)
ReplyDeleteGood one indeed :)
ReplyDeleteThanks :)
DeletePretty neat & straight to the point, thanks!!!
ReplyDelete@Nikita Singh
ReplyDeleteselect is return new array not the original array