Is there a convention for memoization in a method call?

前端 未结 6 1519
清酒与你
清酒与你 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

    I use the memoist gem, which lets you easily memoize a method without having to alter your original method or create two methods.

    So for example, instead of having two methods, file_size and calculate_file_size, and having to implement the memoization yourself with an instance variable:

    def file_size
      @file_size ||= calculate_file_size
    end
    
    def calculate_file_size
      # code to calculate the file size
    end
    

    you can just do this:

    def file_size
      # code to calculate the file size
    end
    memoize :file_size
    

    Each memoized function comes with a way to flush the existing value.

    object.file_size       # returns the memoized value
    object.file_size(true) # bypasses the memoized value and rememoizes it
    

    So calling object.file_size(true) would be the equivalent of calling object.calculate_file_size...

提交回复
热议问题