0

I have a problem with my each loop. The line that prints programdetail.name and programdetail.bodypart doesn't print the value. Also do you know how can I make this loop a little bit more efficient? I want to print first 2 items with class "odd" and the other 2 with non-class. So and so forth.

<% @counter = 0 %>
<% @program.programdetails.each do |programdetail| %>
    <% @counter = @counter + 1 %>
    <% @counter = @counter % 3 %>
    <% if (@counter == 0)
      @counter -= 1
    end %>
    <%= '<h3 class="odd"><span class="moduleLabel"> #{programdetail.name}</span><span class="moduleDescription">#{programdetail.bodypart}</span></h3>' if @counter != 0 %>
    <%= '<h3><span class="moduleLabel">#{programdetail.name}</span><span class="moduleDescription">#{programdetail.bodypart}</span></h3>' if @counter != 0 %>

<% end %>
2
  • I'd recommend you to use the cycle helper Commented May 16, 2013 at 20:58
  • I'm surprised it prints any of the values, since you're using string interpolation inside single-quoted strings. That should only work inside dobule-quoted strings. Commented May 17, 2013 at 7:59

1 Answer 1

3

cycle helper could have worked, if you wanted odd/even combo, or over a collection:

<% @program.programdetails.each do |programdetail| %>

  <h3 class="<%= cycle("odd", "odd", "", "") %>
    <span class="moduleLabel"><%= programdetail.name %></span>
    <span class="moduleDescription"><%= programdetail.bodypart %></span>
  </h3>

<% end %>

To fix your code:

<% @counter = 0 %>
<% @program.programdetails.each do |programdetail| %>
  <% @counter = (@counter % 4) + 1 %>
  <h3 class="<%= ((1..2).cover?(@counter))? 'odd': '' %>">    
    <span class="moduleLabel"><%= programdetail.name %></span>
    <span class="moduleDescription"><%= programdetail.bodypart %></span>
  </h3>
<% end %>
Sign up to request clarification or add additional context in comments.

4 Comments

Your solution always print out "odd" class to h3 tag.
Also because the first solution prints class="" for 3 and 4th elements, the CSS got very bad. So, is there a solution to not print class="" for every 3 and 4th element?
<h3 "<%= cycle("class='odd'", "class='odd'", "", "") %>
@Yagiz: Have also corrected the second code. Earlier one was logically wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.