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?
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 %>
The most readable way I find is following:
<%= @user.settings.each do |s| %>
<% if @user.settings.first == s %>
<% # Your desired stuff %>
<% end %>
<% end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With