Posted By

noah on 02/20/09


Tagged

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


Versions (?)


Advertising

Submit Site


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 



Website Promotion
DIRECTORY
is a crucial factor for all websites that need to gain better organic search engine rankings and increase website traffic.
Submitting your website as part of your Web Promotion strategy to our SEO friendly and high traffic Business Directory for review is an excellent way to gain a valuable backlink and increase your websites visibility online.

Submit Site


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
Expand | Embed | Plain Text
  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.

Download royalty free graphics