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
    • 244
    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.

    a = [5,10,15,20]
     => [5, 10, 15, 20] 
    a.each {|t| t+2}
     => [5, 10, 15, 20] 
    a.each {|t| puts(t+2)}
    7
    12
    17
    22
     => [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.

    a = [1,2,3,4]
    
    a.object_id
     => 76272700
    
    a.collect {|x| x*3}
    => [3, 6, 9, 12]
    
    a.object_id
    =>76337640
    
    puts a
     => [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

    c = [1,2,3,4]
     => [1, 2, 3, 4] 
    c.object_d
     => 76350610 
    
    c.map {|x| x*5}
     => [5, 10, 15, 20] 
    
    p c.object_id
     => 76350610 
    
    p c
    => [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
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: