Possible Duplicate:
Ruby – What is the difference between map, each and collect?
I have looked in Ruby-Doc also but i cant understand the difference between
map
each
iterators.It would be great if you could give an example and explain.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
eachsimply 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:This is simply a nicer, more universal way of doing a traditional iterating
forloop, andeachis much preferred overforloops in Ruby (in fact, I don’t think I’ve ever used aforloop 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:So it “maps” each element to a new one using the block given, hence the name “map”. Note that neither
eachnormapthemselves modify the original collection. This is a concise, functional alternative to creating an array and pushing to it in an iterative loop.