在 Ruby 中合并整数(在 Rails 上)
我有一个类,其中包含两个整数(a 和 b)和对实体的引用。
我希望能够报告班级中所有 a 和 b 的总和。
例如,我可能有三个记录:
Entity 1 2 3
a 5 9 3
b 8 1 2
我希望 a 的综合结果为 17,b 的综合结果为 11。
我对最佳方法感兴趣。现在我可以即时汇总所有内容,但如果有很多记录,速度可能会很慢。
或者,我可以维护一个假实体,其中包含合并结果,并在每次更新任何其他对象时更新。
或者我可以有一个不同的班级来合并日期?
所有的想法都受到赞赏。
谢谢 克里斯
I have a class which contains two integers (a and b) and a reference to an entity.
I want to be able to report back on the sum of all the a's and b's within the class.
E.g. I might have three records:
Entity 1 2 3
a 5 9 3
b 8 1 2
I want my consolidated result for a to be 17, and for b 11.
I'm interested in view on the best approach to this. Now I could sum everything on the fly, but if there are lots of records that might be slow.
Or I could maintain a fake entity which contains the consolidated result and is updated each time any of the other objects are update.
Or I could have a different class for consolidated date?
All thoughts appreciated.
Thanks
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您需要一个类方法,例如:
如果您希望缓存它,您可以有一个名为
@@cache_invalid
的类变量,并随时将其设置为 truea 或
b
更改。然后您可以检查这一点,如果为 false,则返回缓存值,如果为 true,则运行上面的代码(我现在已经编辑了代码以包含此更改)。I think you need a class method, something like:
If you want it cached, you could have a class variable called
@@cache_invalid
for example, and set this to true any timea
orb
change. Then you could check this, and return a cached value if false, and run the code above if true (I've now edited the code to include this change).最简单的方法是在类中跟踪此信息。例如,假设我们有多个 FruitBasket,其中可能包含任意数量的
苹果
和香蕉
。任何时候我们都想知道所有篮子里苹果和香蕉的总数。让我们看看它的实际效果:
到目前为止,一切都很好。再来一个篮子怎么样?
现在让我们修改第一个篮子的内容:
就是这样!
The simplest way is to track this information in the class. For example, suppose we have a number of FruitBaskets that may contain any number of
apples
andbananas
. At any moment we want to know the total number of apples and bananas in all the baskets.Let's see it in action:
So far, so good. How about another basket?
And now let's modify the contents of the first basket:
There you go!
我看到您可以选择两种方法:
a
和b
的总和,总是在任何这些更改时您应该了解以上哪种型号更适合您的需求。我会将急切方式按以下方式放置:
惰性方式应该遍历所有创建的 ABCounter 实例并对
a
和b
的值求和>。I see two ways you might choose from:
a
andb
eagerly, always when any of these changeYou should know which model of the above fits your needs more. I would put the eager way the following way:
The lazy way should go through all created instances of
ABCounter
and sum up the values ofa
andb
.