Distinct difference between collect and each?

RoR picture RoR · Sep 2, 2010 · Viewed 7.5k times · Source

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

Answer

Brian picture Brian · Sep 2, 2010

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