Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 289
Wes Foster Avatar asked Jan 21 '13 20:01

Wes Foster


2 Answers

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 %>
like image 130
MrYoshiji Avatar answered Nov 10 '22 21:11

MrYoshiji


The most readable way I find is following:

<%= @user.settings.each do |s| %>
  <% if @user.settings.first == s %>
    <% # Your desired stuff %>
  <% end %>
<% end %>
like image 7
Arslan Ali Avatar answered Nov 10 '22 21:11

Arslan Ali