me

def Inject & Me - BFFs

posted_by :Amos, :on => 'September 6th, 2008'

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 1 if self == 0
    (1..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[-1] == 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?

end

2 Responses to “Inject & Me - BFFs”

  1. Jeremy Henty Says:

    You have a syntax error in factorial: "self = 0" should be "self == 0". Also two bugs: 0.factorial ==> 0 , but it should be 1 . 1.factorial ==> nil , but it should be 1 . Try removing "return 0 if self = 0" and changing "(2..self).inject" to "(2..self).inject(1)".

  2. Amos Says:

    Thanks, Jeremey. I can't do 2..self if self is one because you can have a range that is backward. But I updated it. Just some typos.

Sorry, comments are closed for this article.

end