What is the difference between Array#map and Array#each ?
What is the difference between Array#map and Array#each ?
In Ruby, Array#map
and Array#each
are both methods used for iterating over collections, such as arrays, but they serve different purposes and have distinct behaviors:
each
method is to iterate over a collection and perform an action on each element. It is used for its side effects, meaning it doesn’t change the original collection but instead executes a block of code for each element[1].each
method always returns the original collection itself, whether it’s an array or a hash. It doesn’t modify the collection or create a new one[1][5].numbers = [1, 2, 3, 4, 5]
numbers.each { |num| puts num * 2 }
each
iterates over the numbers
array, doubling each element, but it doesn’t change the array itself[1].map
method is to iterate over a collection and transform each element based on the provided block of code. It is used when you want to create a new array with the modified elements from the original collection[1][2][3][4].map
method returns a new array containing the results of applying t...middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào