We Recommend

Beginning Ruby: From Novice to Professional Beginning Ruby: From Novice to Professional
Beginning Ruby is a thoroughly contemporary guide for every type of reader wanting to learn Ruby, from novice programmers to web developers to Ruby newcomers. It starts by explaining the principles behind object-oriented programming and within a few chapters builds toward creating a genuine Ruby application.


Posted By

noah on 02/20/09


Tagged

rails ruby index iteration loop iterator last begin first haml end each


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

webstic


Detect the first and last iteration of a loop in Ruby


Published in: Ruby 


URL: http://www.ruby-doc.org/core/classes/Enumerable.html#M003168

It's great that, at the times I really need it, I can ask for Ruby help on #nyc.rb:

 <capn_bluebeard> how can I detect the first or last iteration of a loop in
                  Ruby or Rails?                       
 <fhwang> what sort of loop? an array loop?
 <fhwang> or something else?
 <harrisj> f == array.first?
 <fhwang> in case of an array you want #each_with_index
 <capn_bluebeard> yah each_with_index would do it, thanks much 
 <capn_bluebeard> I'm looping through an array printing LIs and I want to apply
                  css classes to the first and last LIs respectively
  1. - @random_pubs[0..3].each_with_index do |pub, count|
  2. %li{:class => (count > 0 ? (count == 3 ? 'last' : '') : 'first')}
  3. .description= pub.desc

Report this snippet 

You need to login to post a comment.