Member-only story

Replicating JavaScript’s callbacks and closures with Ruby’s yield and lambda

Kevin Kim
3 min readJun 4, 2018

--

Lately, I have been fiddling around with trying to replicate some JavaScript functions as Ruby methods.

A particular one that I have been tinkering with has been JavaScript’s Array.protype.map() method and implementing my own custom Array.prototype.myMap() method like so:

JavaScript: Array.prototype.myMap()

Array.prototype.myMap = function(cb) {
const mappedArr = [];
for (let elem of this) {
mappedArr.push(cb(elem));
};
return mappedArr;
};
[2,4,6].myMap((num) => { return num * 3 }); // [6, 12, 18]

Ruby: Array #my_map

The closest Ruby equivalent that I could come up with was the following:

class Array
def my_map
mapped_arr = []
self.each do |elem|
mapped_arr << yield(elem)
end
mapped_arr
end
end
[2,4,6].my_map { |num| num * 3 }#=> [6, 12, 18]

It looks pretty much identical here, JavaScript’s callback function denoted here as cb gets replaced as Ruby’s reserved yield keyword, and JavaScript’s this gets replaced with Ruby’s self.

--

--

No responses yet