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
:
1 2 3 |
a=%w(A C C T) puts a.map.with_index {|x,index| "#{index}:#{x}"} |
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:
1 2 3 4 5 6 7 |
# Count differences between the two a=%w(A C C T) b=%w(A C C G) differences = a.each_with_index.inject(0) do |s,(c,pos)| s += (c != b[pos]) ? 1 : 0 end |
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.