Difference between map and collect in Ruby?

后端 未结 6 1415
遥遥无期
遥遥无期 2020-11-28 00:26

I have Googled this and got patchy / contradictory opinions - is there actually any difference between doing a map and doing a collect on an array

6条回答
  •  Happy的楠姐
    2020-11-28 01:15

    I've been told they are the same.

    Actually they are documented in the same place under ruby-doc.org:

    http://www.ruby-doc.org/core/classes/Array.html#M000249

    • ary.collect {|item| block } → new_ary
    • ary.map {|item| block } → new_ary
    • ary.collect → an_enumerator
    • ary.map → an_enumerator

    Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.
    If no block is given, an enumerator is returned instead.

    a = [ "a", "b", "c", "d" ]
    a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
    a                          #=> ["a", "b", "c", "d"]
    

提交回复
热议问题