简体   繁体   English

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

[英]DRYest way to check if in the first iteration of an .each loop in Ruby/Rails

In my .erb , I have a simple each loop: 在我的.erb ,我有一个简单的each循环:

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

What is the simplest way to check if it's currently going through its first iteration? 检查它是否正在进行第一次迭代的最简单方法是什么? I know I could set i=0...i++ but that is just too messy inside of an .erb . 我知道我可以设置i=0...i++但是在.erb里面太乱了。 Any suggestions? 有什么建议么?

It depends on the size of your array. 这取决于您的阵列的大小。 If it is really huge (couple of hundreds or more), you should .shift the first element of the array, treat it and then display the collection: 如果它真的很大 (几百或更多),你应该.shift数组的第一个元素,处理它,然后显示集合:

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

Or you can use .each_with_index : 或者您可以使用.each_with_index

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

The most readable way I find is following: 我发现最可读的方式如下:

<%= @user.settings.each do |s| %>
  <% if @user.settings.first == s %>
    <% # Your desired stuff %>
  <% end %>
<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM