Reputation: 1370
I have an array of posts with the following numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
In my ERB I have the following:
<% @post.each_slice(2) do |post, b| %>
<% if post.number != 1 %>
<%= post.number %>
<%= image_tag post.post_image %>
<%= b.number %>
<%= image_tag b.post_image %>
<% end %>
<% end %>
Basically I want rows of the following:
[2, 3]
[4, 5]
[6, 7]
[8, 9]
[10]
When I use the code above I end up with:
[3, 4]
[5, 6]
[7, 8]
[9, 10]
I kind of understand why. I'm basically saying slice into two and then I'm saying "well get rid of 1" so that gets rid of 1 and 2. What's the simplest way to say each_slice starting at index 1?
Upvotes: 0
Views: 316
Reputation: 51151
You can easily get rid of the first element of an array to iterate over the rest (in a way you want), using []
operator:
<% @post[1..-1].each_slice(2) do |post, b| %>
# ...
<% end %>
also, I guess you should check if the second post exists (in case your array is even, like in your example), like this:
<% if b %>
<%= b.number %>
<%= image_tag b.post_image %>
<% end %>
Upvotes: 2
Reputation: 1431
Do something like this
<% @post.drop(1).each_slice(2) do |post, b| %>
# ...
<% end %>
This will produce output like this.
[2, 3]
[4, 5]
[6, 7]
[8, 9]
[10]
Upvotes: 3