Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • each, collect and map in ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 389
    Comment on it

    1> 'each' will loop through each element of the array and evaluate whatever is return inside the block, but it returns the original array without any change.

    1. a = [5,10,15,20]
    2. => [5, 10, 15, 20]
    3. a.each {|t| t+2}
    4. => [5, 10, 15, 20]
    5. a.each {|t| puts(t+2)}
    6. 7
    7. 12
    8. 17
    9. 22
    10. => [5, 10, 15, 20]

    (Thus we see that whatever is written inside the each block is evaluated and the original array is returned at the end)


    2>'collect' returns the new array which is created as the result of executing the specified block for every item of the given array.

    1. a = [1,2,3,4]
    2.  
    3. a.object_id
    4. => 76272700
    5.  
    6. a.collect {|x| x*3}
    7. => [3, 6, 9, 12]
    8.  
    9. a.object_id
    10. =>76337640
    11.  
    12. puts a
    13. => [1, 2, 3, 4]

    (Thus we can see collect returns a new array after performing the operations defined in the block on each element of original array, leaving the original array intact)

    3> 'map' is similar to 'collect'. There is no specific difference between them in functionality, both of them perform the same thing

    1. c = [1,2,3,4]
    2. => [1, 2, 3, 4]
    3. c.object_d
    4. => 76350610
    5.  
    6. c.map {|x| x*5}
    7. => [5, 10, 15, 20]
    8.  
    9. p c.object_id
    10. => 76350610
    11.  
    12. p c
    13. => [1, 2, 3, 4]

    (Thus we can see map also returns a new array after performing the operations defined in the block on each element of original array, leaving the original array intact)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: