Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?)

like image 863
grautur Avatar asked Feb 24 '23 12:02

grautur


2 Answers

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

like image 191
Michael Kohl Avatar answered Mar 15 '23 09:03

Michael Kohl


You could always subclass array and define it there. Say if you had AdderArray < Array you could find the sum like this:

AdderArray.new(a1).sum

Or you could just define a helper library:

ArrayHelper.sum(a1)

It's really up to you what to do. I don't even see a problem with monkey patching (what's the chance someone is going to make an array method called sum that doesn't sum?). Even if a conflict does end up occurring, you could always rename it to sum_members after the fact.

like image 38
Karl Avatar answered Mar 15 '23 10:03

Karl