Is there a convention for memoization in a method call?

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

    I usually use begin, end as per your first example, but if there's a bit more code, I just look if the variable exists, no need to create another method just for that.

    def some_method
      return @some_method if @some_method
      # lot's of code
      @some_method
    end
    

提交回复
热议问题