DRYest检查是否在Ruby/Rails中的.each循环的第一次迭代中的方法

Wes*_*ter 21 each loops ruby-on-rails ruby-on-rails-3

在我.erb,我有一个简单的each循环:

<%= @user.settings.each do |s| %>
  ..
<% end %>
Run Code Online (Sandbox Code Playgroud)

检查它是否正在进行第一次迭代的最简单方法是什么?我知道我可以设置i=0...i++但是内部太乱了.erb.有什么建议?

MrY*_*iji 31

这取决于您的阵列的大小.如果它真的很大(几百或更多),你应该.shift是数组的第一个元素,对待它然后显示集合:

<% user_settings = @user_settings %>
<% first_setting = user_settings.shift %>
# do you stuff with the first element 
<%= user_settings.each do |s| %>
  # ...
Run Code Online (Sandbox Code Playgroud)

或者您可以使用.each_with_index:

<%= @user.settings.each_with_index do |s, i| %>
  <% if i == 0 %>
    # first element
  <% end %>
  # ...
<% end %>
Run Code Online (Sandbox Code Playgroud)


Ars*_*Ali 7

我发现最易读的方式如下:

<%= @user.settings.each do |s| %>
  <% if @user.settings.first == s %>
    <% # Your desired stuff %>
  <% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)