HAML and "each" last index by Vivien Leroy and wrote 30 September 2012

Still coding my blog, I just encountered a quite simple problem. How to distinguish the last element from a Ruby each loop.

Well it's quite simple in fact and here's how to do it :

- @posts.each_with_index do |post, index|
  = render post
  - if index != @posts.size - 1

So you replace each by each_with_index and now you get the index along with the object and you can easily check if it's last object by querying the size of the array.

Update (as @Kaoo pointed out there's an even more clean solution) :

- @posts.each do |post|
  = render post
  - if post != @posts[-1]

Now you're good to go !