0

I have 100 shoes with shoe names. I don't want to display all 100 in a row, I want to display 5, then a green box, then the next 5, and the same green box... but there is something wrong with my code.

<% @shoes.each.with_index(1) do |shoe, index| %>
  <% while index < 101 do %>
    <%= shoe.name %>
    <% if index % 5 == 0 %>
      <%= Green Box %>
    <% end %>

2 Answers 2

2

You're looking for in_groups_of(x)

<% @shoes.in_groups_of(5) do |shoe_groups| %>
    <% shoe_groups.each do |shoe| %>
         <%= shoe.name %>
    <% end %>
    <%= 'Green Box' if shoe_groups.size % 5 == 0 %>
<% end %>
Sign up to request clarification or add additional context in comments.

5 Comments

in this case the if shoe_groups % 5 == 0 isn't needed, since in_groups_of will return 5 shoes, so just need to print out the Green Box code after iterating over the shoes in the group.
Well, that wouldn't keep to his/her requirements as if the last group only had 4 shoes, you wouldn't display Green Box.
in_groups_of yields an array, array doesn't accept a '%' message, So it will error out., if you remove the if statement, it wil echo the green box after each group (even the last one if it has < 5,).
@Doon, you are correct. forgot to get the size. Updated. Thank you.
Should be @shoes.in_groups_of(5, false) . It pads remaining slots with nil, so the code will call nil.name whenever it divides the group by 5 and gets a remainder. apidock.com/rails/Array/in_groups_of
0

Your syntax is wrong in several places - the enumerator is wrong, you are missing several end statements. Also, even though index is not a reserved word, the generally accepted style for an index is a single-letter variable like i. It should be

<% @shoes.each_with_index(1) do |shoe, i| %>
  <% while i < 101 do %>
    <%= shoe.name %>
    <% if i % 5 == 0 %>
      <%= Green Box %>
    <% end %>
  <% end %>
<% end %>

(But personally, I would not do the index < 101 block in the view - I would make sure that the controller that generates @shoes and sends it to the view only sends 100 elements in the array)

1 Comment

the inner while loop here is not needed and will cause an infinite loop. , the outer each_with_index will iterate over the loop just fine. and each_with_index doesn't take an argument

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.