How can I save the value of an instance method?

落花浮王杯 提交于 2021-02-07 10:41:32

问题


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?

Say I have two items:

<% if method_true %>
  do something
<% end %>
<% if method_true %>
  do something else
<% end %>

If method_true == true, how can I just pass the value true through the two ifs instead of calculating it every time?


回答1:


I'm sure there's a more sophisticated answer out there, but for my app I just saved the value in an instance variable.

model

def method_true
  #...
end

view

<% if @model.method_true.true? %>
  <% @x = true %>
<% end %>

After that, you can use

<% if @x == true %>

instead of

<% if @model.method_true.true? %>

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.




回答2:


You could memoize method_true? (Ruby methods that return booleans end in question marks, by convention).

If your expensive calculation can only be true/false:

def method_true?
  if @method_true.nil?
    @method_true = # your expensive calculation
  end
  @method_true
end

If you also care about memoizing nil:

def method_true?
  unless defined?(@method_true)
    @method_true = # your expensive calculation
  end
  @method_true
end

StackOverflow question on memoizing true/false/nil



来源:https://stackoverflow.com/questions/28613335/how-can-i-save-the-value-of-an-instance-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!