如何保存实例方法的值? [英] How can I save the value of an instance method?
问题描述
如果我有一个项目列表,并且对于每个项目我都在调用一个实例方法,那么该如何保存该方法的值并防止在每次调用该方法时对其进行计算?
If I have a list of items, and for every one of them I'm calling an instance method, how can I save the value of the method and prevent it from being calculated every time it's called?
说我有两个项目:
<% if method_true %>
do something
<% end %>
<% if method_true %>
do something else
<% end %>
如果method_true == true,如何将值 true
传递给两个if,而不是每次都进行计算?
If method_true == true, how can I just pass the value true
through the two ifs instead of calculating it every time?
推荐答案
我确定还有一个更复杂的答案,但是对于我的应用程序,我只是将其值保存在实例变量中.
I'm sure there's a more sophisticated answer out there, but for my app I just saved the value in an instance variable.
模型
def method_true
#...
end
视图
<% if @model.method_true.true? %>
<% @x = true %>
<% end %>
之后,您可以使用
<% if @x == true %>
代替
<% if @model.method_true.true? %>
,该方法将不必重新计算.如果 method_true
不为真,那么 @x
将为 nil,所以 if?
条件不会被执行.
and the method won't have to recalculated. And if method_true
isn't true, than @x
will be nil, so the if?
conditionals won't be executed.
这篇关于如何保存实例方法的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!