What's Different Between Each and Collect Method in Ruby

what's different between each and collect method in Ruby

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.

What is the difference between map, each, and collect?

each is different from map and collect, but map and collect are the same (technically map is an alias for collect, but in my experience map is used a lot more frequently).

each performs the enclosed block for each element in the (Enumerable) receiver:

[1,2,3,4].each {|n| puts n*2}
# Outputs:
# 2
# 4
# 6
# 8

map and collect produce a new Array containing the results of the block applied to each element of the receiver:

[1,2,3,4].map {|n| n*2}
# => [2,4,6,8]

There's also map! / collect! defined on Arrays; they modify the receiver in place:

a = [1,2,3,4]
a.map {|n| n*2} # => [2,4,6,8]
puts a.inspect # prints: "[1,2,3,4]"
a.map! {|n| n+1}
puts a.inspect # prints: "[2,3,4,5]"

Distinct difference between collect and each?

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

What are the differences between each, foreach, collect and map?

collect/map are equivalent. They differ from each in that each only executes the block for each element, whereas collect/map return an array with the results of calling the block for each element. Another way to put it might be, each is expected to do something with each element, whereas map is expected to transform each element (map it onto something else).

You could use collect or map anywhere each is used, and your code will still work. But it will probably be slightly less efficient because it collects the results in an array, unless your Ruby implementation realizes it doesn't have to bother creating an array because it's never used.

Another reason to use each instead of map or collect is to help out anyone reading your code. If I see each then I can be like okay, we're about to use each element of the data to do something. If I see map then I'm expecting to see new data being created, based on a remapping of the old data.

With regards to map vs. collect I would say it's a matter of preference, but you should pick one and stick with it for consistency.

Difference between map and collect 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. Wikipedia provides an overview:

The map function originated in functional programming languages but is today supported (or may be defined) in many procedural, object oriented, and multi-paradigm languages as well: In C++'s Standard Template Library, it is called transform, in C# (3.0)'s LINQ library, it is provided as an extension method called Select. Map is also a frequently used operation in high level languages such as Perl, Python and Ruby; the operation is called map in all three of these languages. A collect alias for map is also provided in Ruby (from Smalltalk) [emphasis mine]. Common Lisp provides a family of map-like functions; the one corresponding to the behavior described here is called mapcar (-car indicating access using the CAR operation).

Ruby provides an alias for programmers from the Smalltalk world to feel more at home.


Why is there a different implementation for arrays and enums? An enum is a generalized iteration structure, which means that there is no way in which Ruby can predict what the next element can be (you can define infinite enums, see Prime for an example). Therefore it must call a function to get each successive element (typically this will be the each method).

Arrays are the most common collection so it is reasonable to optimize their performance. Since Ruby knows a lot about how arrays work it doesn't have to call each but can only use simple pointer manipulation which is significantly faster.

Similar optimizations exist for a number of Array methods like zip or count.

Difference between select and collect

Enumerable#collect (or Enumerable#map) returns a result of applying block to each items.

[1, 2, 3, 4].collect { |x| x > 2 }
# => [false, false, true, true]

While Enumerable#select returns an array of filtered items:

[1, 2, 3, 4].select { |x| x > 2 }
# => [3, 4]

Difference Between map and each

each simply iterates over the given enumerable, running the block for each value. It discards the return value of the block, and each simply returns the original object it was called on:

[1, 2, 3].each do |x|
x + 1
end # => [1, 2, 3]

This is simply a nicer, more universal way of doing a traditional iterating for loop, and each is much preferred over for loops in Ruby (in fact, I don't think I've ever used a for loop in Ruby).


map, however, iterates over each element, using the return value of the block to populate a new array at each respective index and return that new array:

[1, 2, 3].map do |x|
x + 1
end # => [2, 3, 4]

So it “maps” each element to a new one using the block given, hence the name “map”. Note that neither each nor map themselves modify the original collection. This is a concise, functional alternative to creating an array and pushing to it in an iterative loop.

Difference between &.each and .each for arrays in ruby?

&.each is an operator and a method. each is only one method.

&., called “safe navigation operator”, allows to skip method call when
receiver is nil. It returns nil and doesn't evaluate method's
arguments if the call is skipped.

So, if the receiver is nil (which isn't the case in your example) it'll just return nil because it doesn't respond to each:

nil&.each
# nil

Otherwise, invoking any non-defined method in an object throws a NoMethodError. And is what you'll get in your second example:

nil.each
# ...
# NoMethodError (undefined method `each' for nil:NilClass)

The documentation about the safe navigation operator is in the Calling Methods documentation. While for each it's in Array.

Is there a default difference between methods with '!' and without, in ruby?

In ruby the main difference is that, the ! methods are selfish, i.e. they apply the changes to the self object. They return nil, when no changes are done, while the non-! methods create new modified object.

In Rails the difference is that, the ! methods are safe versions of non-! methods, that means the ! methods raises an exception when the code encountered an error during execution, while non-! methods just return error state, usually false condition.



Related Topics



Leave a reply



Submit