Pregunta de entrevista de AdvantageClub.ai

How does map(&:to_i) internally works?

Respuesta de la entrevista

Anónimo

16 nov 2019

map is used to execute a block of code for each element of a given Enumerable object, like an Array. The first thing that happens is that, whenever Ruby sees a & for a parameter, it wants this parameter to be a Proc. If this is not the case already, Ruby calls #to_proc on this object to convert it. map iterates over the received list and calls the received Proc on each element, passing it as a parameter. The Proc then executes element.send("to_i"), that is basically the same as "5".to_i, and will return the expected result (convert each element in to integer).