Oct 06

Ruby Enumerables ‘with_index’

Ruby’s Enumerable module provides a couple of methods for stepping through an enumerable with the index of the element as well. However, a couple are missing — there is no inject_with_index or map_with_index. There are a couple of ways of remedying this.

First map_with_index:

You could also monkeypatch.

Unfortunately, inject.with_index won’t work without monkeypatching the module — inject takes either a symbol representing a method or a block. However, you can do:

The ruby forum had an interesting thread about this with comparing the cost between “elegant/maintainable” code and faster — chaining enumerable methods (at least at the time — 2011) increased the cost of execution.

Leave a Reply

%d bloggers like this: