- memoize.rb
module Memoize
def delegate_to_values(*keys)
keys.each do |key|
define_method(key) do
return instance_variable_get(:@bar_cached) if instance_variable_defined?(:@bar_cached)
instance_variable_set(:@bar_cached, rand)
end
end
end
end
- example.rb
# Create proxy method for instance variable @bar_cached ||= rand
# How use?
# exapmle = Example.new
# example.foo
# example.bar
require_relative 'memoize'
class Example
extend Memoize
delegate_to_values(:foo, :bar)
end
exapmle = Example.new
puts "example.foo: #{exapmle.foo}"
puts "example.bar: #{exapmle.bar}"
puts "#{exapmle.bar == exapmle.foo ? 'Correct result!' : 'Not bad attempt!'}"
example.rb
memoization.rb