Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's different between each and collect method in Ruby [duplicate]

Tags:

each

ruby

collect

From this code I don't know the difference between the two methods, collect and each.

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 
like image 848
mko Avatar asked Mar 18 '11 04:03

mko


People also ask

What is collect method in Ruby?

The collect() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum. The object is repeated every time for each enum. In case no object is given, it return nil for each enum.

What is the difference between collect and map in Ruby?

There's no difference, in fact map is implemented in C as rb_ary_collect and enum_collect (eg. there is a difference between map on an array and on any other enum, but no difference between map and collect ). Why do both map and collect exist in Ruby? The map function has many naming conventions in different languages.

What is the difference between each and map in rails?

Array#each executes the given block for each element of the array, then returns the array itself. Array#map also executes the given block for each element of the array, but returns a new array whose values are the return values of each iteration of the block. Note the return value is simply the same array.

What the diff between MAP and each?

The main difference between map and forEach is that the map method returns a new array by applying the callback function on each element of an array, while the forEach method doesn't return anything. You can use the forEach method to mutate the source array, but this isn't really the way it's meant to be used.


1 Answers

Array#each takes an array and applies the given block over all items. It doesn't affect the array or creates a new object. It is just a way of looping over items. Also it returns self.

  arr=[1,2,3,4]   arr.each {|x| puts x*2} 

Prints 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 on 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 it is actually an array of Nil's [nil,nil,nil] because puts x.succ returns nil (even though it prints M AA K).

And

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

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

like image 183
RameshVel Avatar answered Oct 02 '22 00:10

RameshVel