Difference between .each and .collect


I don't understand the difference between .each and .collect. The .each method doesn't work here to double each value of my_array and put the result in the variable doubled. It works if you replace .each with .collect, but I don't know the fundamental reason why.

my_array = [1, 2, 3]

doubled = my_array.each do |x|
    x * 2

puts doubled


"Work" is such a bad word, it's used to avoid saying and even considering what action you mean, even when those details are the subjects being discussed

They both work, but they work differently. Which one suits your purpose better? Well, you'd need to describe the purpose and then go hunting for the corresponding method, or if you have a bunch of methods where you suspect some of them might be what you want then you'd read up on how they behave.

Array methods are described here:


The intended action is explicitly stated: double each value of my_array and put the result in the variable doubled. The .each method does not work to do this; the contents of doubled is the same as the original my_array. Why is that? It's not enough to simply know that .collect will do this; I want to know why I should use one instead of the other.


Ask yourself, does each generate an array?


I guess not. That helps, although the patronizing tone is completely unnecessary. I don't know why everyone has to cop such an attitude. Congratulations, you know more about Ruby than me.


And I thought I was just giving a hint as to their difference.


If I ask about why I'd choose a plane over the eiffel tower for flying, I'd be told to look up what the eiffel tower is.

It's an iron tower, I no longer have the question of why I would choose a plane instead, I'm able to reason that out myself.

Using the word "work" and starting out with the conclusion that only one of them does what you want is detrimental to answering your question and others like it by your self. You're showing that you're doing things stopping you from figuring it out by yourself - I'll be all over that.

Figuring these things out is something developers do constantly, information searching is how things are found out. So I'll reply with "here's how you can find this", not with the answer to the question

And I also need to start by having you back up a few steps where I think you went wrong in finding it out

At some point it's just really difficult to find and/or it has been demonstrated that reasonable ways of figuring it out has been exhausted. That's when I'll answer something directly, but not before.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.