Is there a convention for memoization in a method call?

前端 未结 6 1518
清酒与你
清酒与你 2021-02-19 04:14

I want to avoid reevaluation of a value in method call. Untill now, I was doing this:

def some_method
  @some_method ||= begin
    # lot\'s of code
  end
end
         


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 04:45

    There is one more way, more Java-style I think.

    First of all you should implement annotations, like "Java-style annotations in Ruby" and "How to simulate Java-like annotations in Ruby?".

    Then you should add annotation like _cacheable that will said to method that it should return instance variable and if it is null it should calculate it by invoking method, so your code will be more clear:

    _cacheable
    def some_method
       # do_some_work
    end
    

提交回复
热议问题