Skip to content

Instantly share code, notes, and snippets.

@secretpray
Created November 16, 2022 06:51
Show Gist options
  • Save secretpray/d52ab5e11451c1be6a757a3bf587daa0 to your computer and use it in GitHub Desktop.
Save secretpray/d52ab5e11451c1be6a757a3bf587daa0 to your computer and use it in GitHub Desktop.
  1. 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
  1. 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!'}"
@secretpray
Copy link
Author

secretpray commented Nov 16, 2022

  1. Задание

example.rb

# Create proxy method for instance variable @bar_cached ||= rand
# How use?
# exapmle = Example.new
# example.foo
# example.bar
require_relative 'memoization'

class Example
  extend Memoization

  memoize def foo
    rand
  end

  memoize def bar
    rand
  end, as: :@bar_cached
  
  memoize def sum(x, y)
    x + y
  end
  # 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!'}"
puts "exapmle.sum(3, 4): #{exapmle.sum(3, 4)}"
puts "exapmle.sum(6, 4): #{exapmle.sum(6, 4)}"

memoization.rb

module Memoization
  def memoize(name, as: nil)
    cache_variable_name = as || :"@#{name}"

    has_arguments = instance_method(name).arity.zero?

    prepend Module.new do
      if has_arguments
        cache = {}
        define_method(name) do |*args|
          return cache[args.hash] if cache.key?(args.hash)

          cache[args.hash] = super(*args)
        end
      else
        define_method(name) do
          return instance_variable_get(cache_variable_name) if instance_variable_defined?(cache_variable_name)

          instance_variable_set(cache_variable_name, super)
        end
      end
    end
  end
end

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