+ 1
Ruby - Why do "each" and "map" output differently?
"each" outputs 1,2,3, whilst "map" outputs -1,-2,-3 arr = [1,2,3] puts arr.each{|x| x = -x} puts arr.map{|x| x = -x}
2 Answers
+ 2
I don't code ruby but if it is like js forEach and map:
arr.each iterates causing side effects without mutation. It executes the callback on each element without changing the original values.
arr.map causes a mutation. Original values are changed to the value returned by the caklback.