Multiline method memoization in ruby
Public
23 Jul 13:42

Method memoization in ruby is easy when the method is one line long:

def something
  @something ||= # your calculations
end

But when we have multiple lines it becomes more difficult to do

def something
  return @something if @something
  # your calculations
  # ... 
  # ... 
  @something = # calculated value

But you can still use the simple ||= operator, if you wrap your method in a begin..end block

def something
  @something ||= begin
    # your calculations
    # ...
    # ...
  end
end

Comments

Empty! You must sign in to add comments.