Posted By

vanne on 01/20/07


Tagged

rails ruby


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


Using Enumerable#select to create a specific array


 / Published in: Ruby
 

URL: http://errtheblog.com/post/608

Useful for when you need to do a find and map specific results to an array for use later

  1. #Instead of using:
  2. books = Book.find(:all, :order => 'id desc', :limit => 20)
  3. comics = []
  4. books.each do |book|
  5. comics << book if book.item_type == 'Comic'
  6. end
  7.  
  8. #OR
  9. comics = Book.find(:all, :order => 'id desc', :limit => 20).map {|book| [book] unless book.item_type == 'Comic'}.flatten!
  10.  
  11. #Use this:
  12. books = Book.find(:all, :order => 'id desc', :limit => 20)
  13. comics = books.select { |i| i.item_type == 'Comic' }

Report this snippet  

You need to login to post a comment.