1 2 3 4
def all_shops(products) ids = [] products.collect { |product| product.shops }.flatten.reject { |s| if ids.include?(s.id); true; else; ids.push(s.id); false; end } end
Refactorings
No refactoring yet !
danielharan
July 6, 2008, July 06, 2008 03:31, permalink
1 2 3
def all_shops(products) products.collect { |product| product.shops }.flatten.uniq end
Jeremy Weiskotten
July 7, 2008, July 07, 2008 13:47, permalink
Daniel nailed it. If you're using Rails, or implement Symbol#to_proc the way Rails does, it can be a bit terser.
1 2 3
def all_shops(products) products.map(&:shops).flatten.uniq end
The goal is to return a list of all shop objects that sell a particular bunch of products... Shops that sell each product are already available as "product.shops". My trouble is in preventing a single shop from appearing in the returned shops array more than once, since a single shop might carry multiple products.
* Note * No two shop objects are the same since they have special info about their parent product as attributes.