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.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.numbers = [1, 2, 3, 4, 5]
numbers.each { |num| puts num * 2 }
In this example, each iterates over the numbers array, doubling each element, but it doesn’t change the array itself.Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.