[ Quick edit: Yeah, I screwed up the title and that botched the permalink and now I can't change it. ]
On evedb.info I have Market categories set up as a tree (acts_as_tree) which means when drilling down the categories: "Ammunition & Charges -> Frequency Crystals -> Advanced Beam Laser Crystals", for example I would like to create breadcrumbs to get back to those parent categories.
Before I got Enumerable#inject working I was mangling with all sorts of recursion. It wasn't pretty.
Then along came the day when I wanted to rewrite it to make sense!
-
def marketHierarchy(cat)
-
cat.ancestors.reverse.inject("") { |link_str,a_cat| link_str += link_to(h(a_cat),market_path(a_cat)) + " -> " }
-
end
This bit of voodoo works brilliantly.
What it does, for those who aren't familiar with Enumerable#inject is:
For each element in the ancestors of the passed MarketCategory do:
- Do the block, but first initialize link_str to ""
- Append a link to link_str and ->
- After the link is appended pass set link_str for the next element in the ancestors list to the result of the block (link_str)
And then just return the result of the block, the final link_str.
The Enumerable#inject method is really cool!

