Câu hỏi phỏng vấn Ruby
Câu hỏi

What is the difference between Array#map and Array#each ?

Câu trả lời

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:

Array#each

  • Purpose: The primary purpose of the 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].
  • Return Value: The 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].
  • Example:
    ruby Copy
    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[1].

Array#map

  • Purpose: The primary purpose of the 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].
  • Return Value: The map method returns a new array containing the results of applying t...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is the main difference between procs and lambdas?

senior

When might you encounter a LocalJumpError ?

junior

Can you call a private method outside a Ruby class using its object?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào