shlogg · Early preview
Jetthoughts Dev @jetthoughts

Memoize Boolean Results With Defined?

Use `defined?(@_result)` instead of `||=` for memoization when method can return false or nil.

TL;DR: if method can return false or nil, and you want to memoize it, use defined?(@_result) instead of ||=.
Memoization is a useful technique which helps to achieve cleaner and more efficient code. When some expensive method of an object is called, we save its value to an instance variable, so that we don’t have to do those heavy calculations again.

class Book
  def word_count
    @_word_count ||= sections.sum do |section|
      section.paragraphs.map(&:text).sum { |para| para.scan(/\w+/).size }
    end
  end 
end

    
    

    
    




The ||= is a conditional assignment operator which t...