23

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?

Wes Foster
  • 8,770
  • 5
  • 42
  • 62
  • 2
    What's the ultimate goal? Would it be easier to just do something with the first element, then iterate over the rest? It keeps the conditional logic out. – Dave Newton Jan 21 '13 at 20:12
  • @DaveNewton that sounds like an interesting approach, you should post an example :) – Peter Brown Jan 21 '13 at 20:27

2 Answers2

36

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 %>
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • 1
    Yes! It's amazing how quickly you can forget things like this when you hardly use them. Thanks! – Wes Foster Jan 21 '13 at 20:16
  • StackOverflow made me wait 10 minutes before accepting the answer, no worries on that. And this code is for simply displaying the first item in the loop a little differently than the rest. I guess I could have separated them, but it seems like a loop would be easier and keep the group of code more contained. You hit the nail on the head – Wes Foster Jan 21 '13 at 20:34
7

The most readable way I find is following:

<%= @user.settings.each do |s| %>
  <% if @user.settings.first == s %>
    <% # Your desired stuff %>
  <% end %>
<% end %>
Arslan Ali
  • 17,418
  • 8
  • 58
  • 76