Using Enumerable#select to create a specific array


/ Published in: Ruby
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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' }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.