Search code examples
rubymonkeypatching

Safely adding a `sum` method to Array class


I'm doing a lot of array summing in my code, so I'm thinking of monkey-patching the Array class to include a sum method (that sums all the elements in the array):

class Array
  def sum
    self.inject{ |s, t| s + t }
  end
end

However, I've never monkey-patched anything in shared code before, and I doubt that this is a "safe" thing to do (e.g., maybe someone else has already defined a sum method in Array).

So what's the best way to be able to sum arrays in the code I'm writing, without having to write arr.inject{ |s, t| s + t } every time? Is there a safe way to monkey-patch? Can I use a module somehow? Or should I just write a helper method somewhere that takes in an array and returns the sum (i.e., def sum_array(arr); return arr.inject{ |s, t| s + t }; end)? (Or is there some totally other approach?)


Solution

  • inject can actually take a symbol argument, so all you really have to write is arr.inject(:+), which I think doesn't really need a shorter form.

    http://www.ruby-doc.org/core/classes/Enumerable.html#M001494