Fd1dab0af492d22ae0dc51d120a7c236

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.

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 !

880cbab435f00197613c9cc2065b4f5a

danielharan

July 6, 2008, July 06, 2008 03:31, permalink

1 rating. Login to rate!
1
2
3
def all_shops(products)
    products.collect { |product| product.shops }.flatten.uniq
end
5170ca260dbd2cdfd5a887a4dba7636f

Jeremy

July 7, 2008, July 07, 2008 13:47, permalink

1 rating. Login to rate!

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
Fd1dab0af492d22ae0dc51d120a7c236

Eric

July 8, 2008, July 08, 2008 17:47, permalink

No rating. Login to rate!

Thank you Daniel, Thank you Jeremy!!!

Your refactoring





Format Copy from initial code

or Cancel