Where is map_with_index in Ruby?

Rubyists generally don’t use for loops, because using iterators (each, inject, map) is far easier, to both read and write. But sometimes, we fall back to using each as a for loop when we don’t have to. The enumerable module is pretty rich when it comes to dealing with collections and lists. each_cons, each_with_index, zip, select, reject, and transpose are ones I find myself using often, once I figured out what they were doing.

However, one that eluded me was why there wasn’t a map_with_index in Ruby? Ends up that it’s redundant, because you can simply do this:

%w(a b c d e).each_with_index.map { |val, ind| [val, ind] }

And voila! You have map_with_index. I wonder what other combinations I’m missing out on? Have any of you discovered any?



One thought on “Where is map_with_index in Ruby?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s