Under the hood – Ruby methods Array#map, Array#inject

In the spirit or writing some Ruby methods I’m going to add three in this post. We’ll begin with mapping elements of an Array.

class Array
    def rb_map
        n_array = []
        self.each { |elm| n_array << yield(elm) }
        n_array
    end
end

Then we do Inject,

class Array
    def rb_inject initial = nil
        value = initial
        self.each { |elm| value = yield(value,elm) }
        value
    end
end

And finally, let’s revisit map using our inject:

class Array
    def new_map_using_inject
        rb_inject([]) { |set, elm| set << elm }
    end
end

You’ll notice I did not do any error handling. That’s not the point of the exercise; we want to know what the methods we call daily do behind the scenes.

Leave a Reply

Your email address will not be published. Required fields are marked *