GEspinha GEspinha - 4 months ago 16
Ruby Question

Get last of slice in each loop in Rails

I have the following sliced each loop:

<% @group.each_slice(3).with_index do |k, i| %>
<% k.each do |k| %>
<% end %>
<% end %>


How can I determine that I am on the last slice? Something like this:

<% k == @group.each_slice(3).last %>

Answer

It would be a good idea to precalculate @group.each_slice(3) (better to do it in a controller)

<% slices = @group.each_slice(3).to_a %>

You could divide your logic for head slices and last slice

<% slices[0..-2].with_index do |k, i| %>
<% end %>

<% slices[-1].with_index do |k, i| %>
<% end %>

Or you could check if it is last slice by its index

<% slices.with_index do |k, i| %>
  <% if i == slices.size - 1 %>
    ...
  <% else %>
    ...
  <% end %>
<% end %>