安全地将“sum”方法添加到 Array 类
我在代码中进行了大量的数组求和,因此我正在考虑对 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您始终可以子类化数组并在那里定义它。假设您有
AdderArray < Array
你可以这样找到总和:或者你可以定义一个辅助库:
这完全取决于你要做什么。我什至没有看到猴子修补的问题(有人会创建一个名为
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:Or you could just define a helper library:
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 tosum_members
after the fact.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 isarr.inject(:+)
, which I think doesn't really need a shorter form.http://www.ruby-doc.org/core/classes/Enumerable.html#M001494