Lazy initialization in Ruby using lambda

# 05 May 2010

If you want to use lazy initialization in Ruby the ||= trick is an easy and readable way to do it.

class Tree
  def estimated_yield
    @estimated_yield ||= get_estimated_yield
  end
private
  def get_estimated_yield
    n = 0
    branches.each { |branch| n += branch.fruits + branch.berries }
    n
  end
end

Rather than bury the actual “get fruit” logic inside of another function though, I’ve found it handy to use a Proc if that logic doesn’t need to be re-used elsewhere.

class Tree
  def estimated_yield
    @estimated_yield ||= lambda {
      n = 0
      branches.each { |branch| n += branch.fruits + branch.berries }
      n
    }.call
  end
end