Posted over 5 years ago. Visible to the public.

Know Ruby: with_index

Have you ever used with_index? Not each_with_index which is similar but slightly different. Did you know that you can do map.with_index?
Adding with_index to an enumeration lets you enumerate that enumeration. Say that ten times fast. A quick example will clarify that a bit. Let’s say I have a list of three, I don’t know, famous Martians.

martians = ["Marvin", "J'onn J'onzz", "Mark Watney"]

I’ll list them along with their current position in the array.

> martians * .each * .with_index(1) do |martian, i| * puts "#{i}) #{martian}" > end 1) Marvin 2) J'onn J'onzz 3) Mark Watney => ["Marvin", "J'onn J'onzz", "Mark Watney"]

As I mentioned earlier, with_index isn’t limited to each. I could replace each with map in the example above.

> martians * .map * .with_index(1) do |martian, i| * "#{i}) #{martian}" > end => ["1) Marvin", "2) J'onn J'onzz", "3) Mark Watney"]

You probably noticed that I’m passing 1 to with_index. It accepts an integer offset defaulted to 0. I’ve found this to be handy when generating user-facing information. They usually don’t want their lists to be zero-indexed. No more having to do i + 1 inside the block. It’s also useful when you have a dynamic list that starts after some hard-coded entries.

Owner of this card:

Alexander M
Last edit:
over 5 years ago
by Alexander M
Posted by Alexander M to Ruby and RoR knowledge base
This website uses short-lived cookies to improve usability.
Accept or learn more