开发者

How do I access a counter inside a Ruby iteration?

My google skills are failing me big time. If I have a standary Ruby loop like this:

<% @notes开发者_StackOverflow社区.each do |q| %>
<% end>

How do I access a loop counter from inside the loop? Thanks for reading.


Use each_with_index instead of each to get the index:

@notes.each_with_index do |note, idx|
 p idx
 p note
end

Refer to the ruby documentation for more details.


There is no loop counter in the example given. In other languages, this style of loop is usually called a foreach loop. You can still access the current item of the collection by using the variable q in the example given.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜