CodeNewbie Community 🌱

Discussion on: Array.map in Ruby

Collapse
 
djuber profile image
Daniel Uber

Great write-up! Another way to get a feeling for what, and how, map works is to try to re-implement it in terms of each, something like this

def my_map(array)
  # we'll be returning another array
  response = []

  # for each element in the array
  array.each do |element|  
     # yield/pass element to the provided block, push the result into response
     response << (yield element)
   end  

   # return the response
   response
end  
=> :my_map

# kick the tires and double every item in the list:
my_map([1,2,3,4,5]) {|x| x * 2 }
=> [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

The actual implementation of map in the usual ruby interpreter is done in C for efficiency, but you could build it from each instead (and it helps sometimes to have examples of the concept written in the same language you're working with).