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

问题描述 投票:21回答:2

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

<%= @user.settings.each do |s| %>
  ..
<% end %>

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

ruby-on-rails ruby-on-rails-3 loops each
2个回答
30
投票

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

<% user_settings = @user_settings %>
<% first_setting = user_settings.shift %>
# do you stuff with the first element 
<%= user_settings.each do |s| %>
  # ...

或者你可以使用.each_with_index

<%= @user.settings.each_with_index do |s, i| %>
  <% if i == 0 %>
    # first element
  <% end %>
  # ...
<% end %>

2
投票

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

<%= @user.settings.each do |s| %>
  <% if @user.settings.first == s %>
    <% # Your desired stuff %>
  <% end %>
<% end %>
© www.soinside.com 2019 - 2024. All rights reserved.