安全地将“sum”方法添加到 Array 类

发布于 2024-11-26 10:38:58 字数 488 浏览 3 评论 0原文

我在代码中进行了大量的数组求和,因此我正在考虑对 Array 类进行猴子修补以包含 sum 方法(对数组中的所有元素求和):

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

但是,我从未对 Array 类进行猴子修补之前共享代码中的任何内容,我怀疑这是一个“安全”的事情(例如,也许其他人已经在 Array 中定义了 sum 方法)。

那么,能够对我正在编写的代码中的数组求和而无需编写 arr.inject{ |s, t| 的最佳方法是什么?每次都是 s + t }?有没有安全的猴子补丁方法?我可以以某种方式使用模块吗?或者我应该在某处编写一个辅助方法,该方法接受数组并返回总和(即 def sum_array(arr); return arr.inject{ |s, t| s + t }; end )? (或者还有其他完全不同的方法吗?)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷弦 2024-12-03 10:38:59

您始终可以子类化数组并在那里定义它。假设您有 AdderArray < Array 你可以这样找到总和:

AdderArray.new(a1).sum

或者你可以定义一个辅助库:

ArrayHelper.sum(a1)

这完全取决于你要做什么。我什至没有看到猴子修补的问题(有人会创建一个名为sum但不求和的数组方法的机会有多大?)。即使最终确实发生了冲突,您也可以在事后将其重命名为 sum_members

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.

幸福%小乖 2024-12-03 10:38:58

inject 实际上可以接受一个符号参数,所以你真正需要编写的是 arr.inject(:+),我认为它并不需要更短的形式。

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文