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

vanne on 01/20/07


Tagged

rails ruby


Versions (?)


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.