mko mko - 2 months ago 8x
Ruby Question

what's different between each and collect method in Ruby

From this code I don't know the difference between the two methods,


a = ["L","Z","J"].collect{|x| puts x.succ} #=> M AA K
print a.class #=> Array

b = ["L","Z","J"].each{|x| puts x.succ} #=> M AA K
print b.class #=> Array


Array#each takes an array and apply the given block over all the items. And it doesn't affect or produce the new object. Its just a way of looping items. Also it returns self.

  arr.each {|x| puts x*2}

print 2,4,6,8 and returns [1,2,3,4] no matter what

Array#collect is same as Array#map and it applies the given block of code over all the items and returns the new array. simply put 'Projects each element of a sequence into a new form'

  arr.collect {|x| x*2}

returns [2,4,6,8]

And In your code

 a = ["L","Z","J"].collect{|x| puts x.succ} #=> M AA K 

a is an Array but its actually array of Nil's [nil,nil,nil] because (puts x.succ) returns nil. (Though it prints M AA K)


 b = ["L","Z","J"].each{|x| puts x.succ} #=> M AA K

also an Array. But its value is ["L","Z","J"], because it returns self.