Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Collect and Map In Ruby On Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 297
    Comment on it

    Map:

    Map use to take the object of enumerable and returns a new array with the results of running block once for every element in enum, the block is something like

    [1,2,3].map { |a| a+2 }
    and the outcome of
    [1,2,3].map { |a| a+2 } will be [3,4,5]

    If no block is given, an enumerator is returned.

    Collect:

    Collect is a similar method to Map which also takes the enumerable object and a block like this

    [4,5,6].collect { |b| b*3 }
    and evaluates the block for each element and then return a new array with the calculated values.

    so the outcome

    [4,5,6].collect{ |b| b*3 }
    of will be [12,15,18]

    or

    (1..4).collect {|i| i+i }   #=> [2, 4, 6, 8]
    (1..4).collect { "dog"  }   #=> ["dog", "dog", "dog", "dog"]

    Note: Both Map and Collect are alias of each other.Both produce same results.

 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: