Skip to content

Instantly share code, notes, and snippets.

@wkjagt
Last active September 29, 2015 17:45
Show Gist options
  • Save wkjagt/5a4e63755e085e89c5bc to your computer and use it in GitHub Desktop.
Save wkjagt/5a4e63755e085e89c5bc to your computer and use it in GitHub Desktop.

Revisions

  1. wkjagt revised this gist Sep 29, 2015. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions ruby-memoize.md
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,6 @@
    `Memoize` memoizes function return values based on class name, method name, and arguments. This means that this only works for functions that use state / have side effects.


    ```rb
    module Memoize
    def memoize(definition)
  2. wkjagt revised this gist Sep 29, 2015. 1 changed file with 4 additions and 1 deletion.
    5 changes: 4 additions & 1 deletion ruby-memoize.md
    Original file line number Diff line number Diff line change
    @@ -13,7 +13,11 @@ module Memoize
    }
    end
    end
    ```

    Usage

    ```rb
    class A
    class B
    extend Memoize
    @@ -29,7 +33,6 @@ end

    b = A::B.new


    p b.heavy_calculation(4, 20)
    # "calling the original"
    # 80
  3. wkjagt revised this gist Sep 29, 2015. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion ruby-memoize.md
    Original file line number Diff line number Diff line change
    @@ -18,10 +18,12 @@ class A
    class B
    extend Memoize

    memoize def heavy_calculation(a, b)
    def heavy_calculation(a, b)
    p "calling the original"
    a * b
    end

    memoize :heavy_calculation
    end
    end

  4. wkjagt created this gist Sep 29, 2015.
    39 changes: 39 additions & 0 deletions ruby-memoize.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    ```rb
    module Memoize
    def memoize(definition)
    self.send(:alias_method, "__original_#{definition}", definition)

    define_method definition, Proc.new { |*args|
    @__memo ||= {}

    key = "#{self.class.name}##{definition}/#{args.hash}"
    return @__memo[key] if @__memo.key?(key)

    @__memo[key] = send("__original_#{definition}", *args)
    }
    end
    end

    class A
    class B
    extend Memoize

    memoize def heavy_calculation(a, b)
    p "calling the original"
    a * b
    end
    end
    end

    b = A::B.new


    p b.heavy_calculation(4, 20)
    # "calling the original"
    # 80
    p b.heavy_calculation(4, 20)
    # 80
    p b.heavy_calculation(2, 20)
    # "calling the original"
    # 40
    ```