Return to Snippet

Revision: 2236
at January 20, 2007 19:43 by vanne


Initial Code
#Instead of using:
books  = Book.find(:all, :order => 'id desc', :limit => 20)
comics = []
books.each do |book|
  comics << book if book.item_type == 'Comic'
end

#OR
comics  = Book.find(:all, :order => 'id desc', :limit => 20).map {|book| [book] unless book.item_type == 'Comic'}.flatten!

#Use this:
books  = Book.find(:all, :order => 'id desc', :limit => 20)
comics = books.select { |i| i.item_type == 'Comic' }

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

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

Initial Title
Using Enumerable#select to create a specific array

Initial Tags
rails, ruby

Initial Language
Ruby