Skip to content

Instantly share code, notes, and snippets.

@mattconnolly
Created April 1, 2014 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattconnolly/9907062 to your computer and use it in GitHub Desktop.
Save mattconnolly/9907062 to your computer and use it in GitHub Desktop.
A let method to memoize values that could be nil.
module Let
def let(name, &block)
ivar = "@#{name}".to_sym
if instance_variable_defined?(ivar)
instance_variable_get(ivar)
else
instance_variable_set(ivar, instance_eval(&block))
end
end
end
class Thing
include Let
def result
let(:result) { some_expensive_calculation_that_could_return_nil }
end
end
t = Thing.new
t.result #=> calculated result that could be nil
t.result #=> cached result that could be nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment