gpt4 book ai didi

javascript - 在 Ruby 方法中创建缓存

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:28 24 4
gpt4 key购买 nike

JavaScript 中,内存像 Fibonacci 这样的函数是相当简单的:

// In JavaScript

var fibonacci = (function () {
var cache = {}; // cache for future calculations

return function (num) {
if (num < 0) throw new Error('Negative numbers not allowed');
if (num === 0) return 0;
if (num === 1) return 1;

cache[num] = cache[num] || fibonacci(num - 1) + fibonacci(num - 2);
return cache[num];
};
})();

console.log( fibonacci(5) ); // results in 5
console.dir( fibonacci ); // you can inspect the closure scope and see that the cache object saves the values for future use

我试图了解如何在 Ruby 中做类似的事情,不幸的是,我唯一能想到的就是创建一个类并将缓存存储为类变量:

# In Ruby
class Placeholder
@@cache = {}

def fibonacci(num)
raise 'Negative numbers not allowed' if num < 0
return 0 if num == 0
return 1 if num == 1

@@cache[num] ||= fibonacci(num - 1) + fibonacci(num - 2)
end
end

example = Placeholder.new
puts example.fibonacci(5) # results in 5

我不喜欢这个的事实是,当我并不真正打算创建 Placeholder 的实例时,我正在创建一个类结构。 .相反,我这样做只是因为我想将状态保存在 Ruby 类变量中。理想情况下,如果我能够创建一个 module并且有一个module变量,那么这至少可以解决我用 class 实例化的“问题”基于解决方案。 对于在 Ruby 中执行此操作,您有哪些最佳建议?

根据@meagar 的评论更新:

@meagar,你是在建议这样的事情吗?

class Placeholder
attr_reader :cache

def initialize
@cache = {}
end

def fibonacci(num)
raise 'Negative numbers not allowed' if num < 0
return 0 if num == 0
return 1 if num == 1

@cache[num] ||= fibonacci(num - 1) + fibonacci(num - 2)
end
end

FibonacciCalculator = Placeholder.new
puts FibonacciCalculator.fibonacci(5) # results in 5

与我最初的 Ruby 解决方案相比,我已经更喜欢它了,尽管使用 Placeholder 类仍然让我感到不适。

最佳答案

当您不需要实例时,您可以使用带有单例方法的模块:

module Fibonacci
@cache = {}

def self.series(num)
if @cache[num] then return @cache[num]; end
if num < 0 then raise 'Negative numbers not allowed'; end
if num == 0 then return 0; end
if num == 1 then return 1; end

@cache[num] = series(num - 1) + series(num - 2)
end
end

puts Fibonacci.series(5) # results in 5

请注意,对于缓存,Fibonacci 模块上的实例变量与类变量一样有效(对于某些扩展用途,它可能会更好)。它之所以有效,是因为模块 Fibonacci 是 Module 的实例 - 在这方面它与任何其他实例变量相同。

关于javascript - 在 Ruby 方法中创建缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28441821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com