DRYest way to check if in the first iteration of an .each loop in Ruby/Rails
11,208
Solution 1
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 %>
Solution 2
The most readable way I find is following:
<%= @user.settings.each do |s| %>
<% if @user.settings.first == s %>
<% # Your desired stuff %>
<% end %>
<% end %>
Related videos on Youtube
Author by
Wes Foster
Online Marketer - SEO/Marketing Consultant and Owner at WESFED - Software Engineer - Web Developer Follow me on Twitter! @realwesfoster
Updated on July 12, 2022Comments
-
Wes Foster almost 2 years
In my
.erb
, I have a simpleeach
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?-
Dave Newton over 11 yearsWhat'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.
-
Peter Brown over 11 years@DaveNewton that sounds like an interesting approach, you should post an example :)
-
-
Wes Foster over 11 yearsYes! It's amazing how quickly you can forget things like this when you hardly use them. Thanks!
-
Wes Foster over 11 yearsStackOverflow 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