Search code examples
ruby-on-rails-3iterationblock

Rails - Display a title only once in an .each block



Noob question here :)

I'm testing a variable, and if it exists, I'd like to display an .each loop with a title.
Of course, the title should be displayed only once. Is there a way to do it? Any best practice?

<%
@twitter_friends.each do |u|
  if @user = User.is_a_member?(u.id)
%>
    # HERE I'D LIKE TO DISPLAY THE TITLE ONLY AT FIRST ITERATION
    <% @user.name %> is your twitter friend, and is a member.
  <% end %>
<% end %>

Thanks !


Solution

  • I would normally recommend using each_with_index and checking for a zero index, but seeing as you have a conditional in the loop, you should use a check variable like so:

    <% shown_title = false %>
    <% @twitter_friends.each do |u| %>
      <% if @user = User.is_a_member?(u.id) %>
        # HERE I'D LIKE TO DISPLAY THE TITLE ONLY AT FIRST ITERATION
    
        <% unless shown_title %>
          <h1>My Title</h1>
          <% shown_title = true %>
        <% end %>
    
        <% @user.name %> is your twitter friend, and is a member.
      <% end %>
    <% end %>