开发者

How to improve the way I browse an array with .each while trying to keep track of the index ("i") using Ruby?

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 sy开发者_如何学Cntax.

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 ?


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}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜