开发者

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 ar开发者_如何学编程ray):

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜