12

Using arrays what's the main difference between collect and each? Preference?

some = []

some.collect do {|x| puts x}

some.each do |x|
    puts x
end
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
RoR
  • 15,934
  • 22
  • 71
  • 92

2 Answers2

36

array = [] is a shortcut to define an array object (long form: array = Array.new)

Array#collect (and Array#map) return a new array based on the code passed in the block. Array#each performs an operation (defined by the block) on each element of the array.

I would use collect like this:

array = [1, 2, 3]
array2 = array.collect {|val| val + 1}

array.inspect # => "[1, 2, 3]"
array2.inspect # => "[2, 3, 4]"

And each like this:

array = [1, 2, 3]
array.each {|val| puts val + 1 }
# >> 2
# >> 3
# >> 4
array.inspect # => "[1, 2, 3]"

Hope this helps...

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Brian
  • 6,820
  • 3
  • 29
  • 27
  • 2
    +1 for a clear and succinct explanation – Brad Cunningham Sep 02 '10 at 20:11
  • I also thank you for such a good explanation. I asked the same question on codecademy's user forum and got two condescending responses from a couple of self-important jerks. As if it was the dumbest question in the world, and I should be ashamed for asking it. – Kris Hunt Dec 12 '16 at 21:56
5

collect (or map) will "save" the return values of the do block in a new array and return it, example:

some = [1,2,3,10]
some_plus_one = some.collect {|x| x + 1}
# some_plus_one == [2,3,4,11]

each will only execute the do block for each item and wont save the return value.

ase
  • 13,231
  • 4
  • 34
  • 46
  • Thank you very much for your response. So basically with collect, at the same time going through the block it's also saving the values into a new array. So a .collect is somewhat like of an each but with returning an array with return values from each of the blocks? So collect and map are the same thing? Is map deprecated or anything? Any preference one over the other? – RoR Sep 02 '10 at 20:42
  • 3
    `map` and `collect` are the same thing (the same method), it's just different naming conventions. – ase Sep 02 '10 at 20:55