如何将“每个"方法添加到 Ruby 对象(或者我应该扩展 Array)? [英] How do I add 'each' method to Ruby object (or should I extend Array)?
问题描述
我有一个对象结果,它包含一个 result
对象数组以及一些关于数组中对象的缓存统计信息.我希望 Results 对象能够表现得像一个数组.我的第一个切入点是添加这样的方法
I have an object Results that contains an array of result
objects along with some cached statistics about the objects in the array. I'd like the Results object to be able to behave like an array. My first cut at this was to add methods like this
def <<(val)
@result_array << val
end
这感觉很像 c,我知道 Ruby 有更好的方法.
This feels very c-like and I know Ruby has better way.
我也希望能够做到这一点
I'd also like to be able to do this
Results.each do |result|
result.do_stuff
end
但我不确定 each
方法到底在做什么.
but am not sure what the each
method is really doing under the hood.
目前我只是通过一个方法返回底层数组并在其上调用 each ,这似乎不是最优雅的解决方案.
Currently I simply return the underlying array via a method and call each on it which doesn't seem like the most-elegant solution.
任何帮助将不胜感激.
推荐答案
对于实现类数组方法的一般情况,是的,您必须自己实现它们.Vava 的回答显示了一个例子.但是,在您提供的情况下,您真正想要做的是将处理 each
(可能还有其他一些方法)的任务委托给包含的数组,并且可以自动化.
For the general case of implementing array-like methods, yes, you have to implement them yourself. Vava's answer shows one example of this. In the case you gave, though, what you really want to do is delegate the task of handling each
(and maybe some other methods) to the contained array, and that can be automated.
require 'forwardable'
class Results
include Enumerable
extend Forwardable
def_delegators :@result_array, :each, :<<
end
该类将获取所有 Array 的 Enumerable 行为以及 Array <<
运算符,并且它们都将通过内部数组.
This class will get all of Array's Enumerable behavior as well as the Array <<
operator and it will all go through the inner array.
请注意,当您将代码从 Array 继承切换到此技巧时,您的 <<
方法将开始返回而不是对象本身,就像真正的 Array 的 <<
做到了——这可能会让你在每次使用 <<
时声明另一个变量.
Note, that when you switch your code from Array inheritance to this trick, your <<
methods would start to return not the object intself, like real Array's <<
did -- this can cost you declaring another variable everytime you use <<
.
这篇关于如何将“每个"方法添加到 Ruby 对象(或者我应该扩展 Array)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!