Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active August 14, 2021 11:51
Show Gist options
  • Save JoshCheek/c03350076650d29e7db6c65e81e80951 to your computer and use it in GitHub Desktop.
Save JoshCheek/c03350076650d29e7db6c65e81e80951 to your computer and use it in GitHub Desktop.
Memoizing a method with an optional default value without receiving splat args
module Memoize
NOT_SET = Module.new
private_constant :NOT_SET
def memoize(method_name)
meth = method method_name
case meth.parameters.map(&:first)
when [:opt]
define_method method_name do |arg=NOT_SET|
_memoizations.fetch arg do
_memoizations[arg] = (arg == NOT_SET ? meth.call : meth.call(arg))
end
end
else
raise 'unoptimized path goes here'
end
end
private def _memoizations
@_memoizations ||= {}
end
end
extend Memoize
memoize def greeting(name='world')
name # => "world", "Josh"
"Hello, #{name}"
end
greeting # => "Hello, world"
greeting # => "Hello, world"
greeting 'Josh' # => "Hello, Josh"
greeting 'Josh' # => "Hello, Josh"
_memoizations # => {Memoize::NOT_SET=>"Hello, world", "Josh"=>"Hello, Josh"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment