开发者

How do I access a counter inside a Ruby iteration?

开发者 https://www.devze.com 2023-01-07 23:45 出处:网络
My google skills are failing me big time. If I have a standary Ruby loop like this: <% @notes开发者_StackOverflow社区.each do |q| %>

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

精彩评论

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