Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude first (or last) in Rails "each"

How do I exclude the first and/or last item in the Rails each:

<% @shops.each_with_index do |shop, i| %>
  ... some code ...
<% end %>
like image 863
Victor Avatar asked Dec 31 '25 08:12

Victor


1 Answers

Use a range to slice the array before invoking each_with_index:

If you want to exclude the first element, start from 1.

To exclude the last element, end at -2.

@shops[1..-2].each_with_index do |shop, i| 
   ...
end
like image 144
Jacob Relkin Avatar answered Jan 02 '26 02:01

Jacob Relkin