tags:

views:

68

answers:

2

Let's say I'm doing a simple .each but I still want to keep the position in the loop, I can do:

i = 0
poneys.each do |poney|
  #something involving i
  #something involving poney
  i = i + 1
end

This doesn't look very elegant to me. So I guess I could get rid of the .each:

for i in 0..poneys.size-1 do
  #something involving i
end

... or something similar with a different syntax.

The problem is that if I want to access the object I have to do:

for i in 0..poneys.size-1 do
  poney = poneys[i]
  #something involving i
  #something involving poney
end

... and that's not very elegant either.

Is there a nice and clean way of doing this ?

+11  A: 

You can use Enumerable#each_with_index

From the official documentation:

Calls block with two arguments, the item and its index, for each item in enum.

hash = Hash.new
%w(cat dog wombat).each_with_index do |item, index|
    hash[item] = index
end
hash   #=> {"cat"=>0, "wombat"=>2, "dog"=>1}
Tobias Cohen
oooh, cute ! I'll try that right now
marcgg
ok it works perfectly, thank you, you made my day. I was sure there was a better way of doing this
marcgg
+1  A: 

Depends what do you do with poneys :) Enumerable#inject is also a nice one for such things:

poneys.inject(0) do |i, poney|
  i += 1; i
end

I learned a lot about inject from http://blog.jayfields.com/2008/03/ruby-inject.html which is great article.

Priit