在每种方法中使计数器变量增加

时间:2016-03-10 15:55:34

标签: ruby

如何使.each方法中的a变量增加,因此输出将为1,2,3 ...而不是:

<% @all_posts.each do |p, a = 0| %>
  <% a += 1 %>
  <%= a %>
<% end %>

输出:1,1,1 ......

2 个答案:

答案 0 :(得分:1)

只需使用ALTER TABLE orderline ADD constraint fk_item_id FOREIGN KEY (item_id) REFERENCES items(item_id); 代替each_with_index 只有警告:索引从0开始。

each

请参阅http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-each_with_index

答案 1 :(得分:1)

要使其可访问,请在循环外部对其进行初始化。

<% a = 0 %>
<% @all_posts.each do |p| %>
  <% a += 1 %>
  <%= a %>
<% end %>

但更好的方法是:

<% @all_posts.each.with_index(1) do |p, a| %>
  <%= a %>
<% end %>
相关问题