Thursday 18 May 2017

Difference between collect, select, map and each in ruby

To iterate over an array we generally use collect, select, map and each.

All four methods have a similar signature and take a block parameter. The map and collect methods both return an array of values returned by the block. The select method will return the actual values being iterated over if the block evaluates to true

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 original array

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]

2 comments:

  1. Wow great information shared. Cryptex Technologies is a leading Ruby on Rails development companies in India. We build scalable robust secured web app on ror, we pay due stress on error free development. Our ruby on rails developers in india maintain code version with the help of tools. For any queries email us at: info@cryptextextechnologies.com

    ReplyDelete
  2. It is very informative blog and useful post thank you for sharing with us , keep posting learn more about Ruby on rails keep more updating Ruby on Rails Online course Bangalore

    ReplyDelete