This post originated from an RSS feed registered with Ruby Buzz
by Amos King.
Original Post: Inject & Me - BFFs
Feed Title: DirtyInformation
Feed URL: http://feeds.feedburner.com/Dirtyinformation
Feed Description: Information about Ruby/Rails/JRuby/WebDevelpoment/whatever.
I find myself turning to Enumberable#inject more and more. It is such a powerful method, yet I rarely see it used in others' code. Here are a couple of examples of the power of inject.
Adding Facorial to All Integers
class Integer
def factorial
raise 'Cannot take a factorial of a negative number' if self < 0
return 0 if self = 0
(2..self).inject { |total, element| total * element }
end
end
Removing Touching Matching Elements in an Array Until No Touching Elements Match( thanks Eric )
class Array
def remove_touchers
self.inject([]) { |final, element| final == element ? final[0..-2] : final << element }
end
end
So, why aren't there more people using this method? Is it just forgotten? Are you using Enumberable#inject? How are you using it?