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

Wes Foster picture Wes Foster · Jan 21, 2013 · Viewed 10k times · Source

In my .erb, I have a simple each loop:

<%= @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. Any suggestions?

Answer

MrYoshiji picture MrYoshiji · Jan 21, 2013

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:

<% 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:

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