Skip to content

Instantly share code, notes, and snippets.

@stuartc
Created February 2, 2018 12:28
Show Gist options
  • Save stuartc/24ae883815929b792e167c8cd63334f8 to your computer and use it in GitHub Desktop.
Save stuartc/24ae883815929b792e167c8cd63334f8 to your computer and use it in GitHub Desktop.
Memoization Helper
# Replaces repetitive memoization syntax:
# ```
# def foo
# return @_foo if defined? @_foo
# @_foo = 'bar'
# end
# ```
#
# Usage:
#
# ```
# require 'memoize'
#
# class Foo
# def bar
# memoize { 'baz' }
# end
# end
# ```
def memoize(meth = nil)
variable_name = "@_#{meth || caller_locations(1, 1)[0].label}".to_sym
receiver = binding.receiver
if receiver.instance_variable_defined?(variable_name)
receiver.instance_variable_get(variable_name)
else
receiver.instance_variable_set(variable_name, yield)
end
end
@gee-forr
Copy link

gee-forr commented Feb 2, 2018

Nice one @stuartc - am definitely gonna use this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment