我想知道是否有更多"类似Ruby"的方法来记忆Ruby中带有多个参数的函数.这是我想出的一种方法,但不确定它是否是最好的方法:
@cache = {}
def area(length, width) #Just an example, caching is worthless for this simple function
key = [length.to_s, width.to_s].join(',')
if @cache[key]
puts 'cache hit!'
return @cache[key]
end
@cache[key] = length * width
end
puts area 5, 3
puts area 5, 3
puts area 4, 3
puts area 3, 4
puts area 4, 3
Run Code Online (Sandbox Code Playgroud)
参数用逗号连接,然后用作存储@cache变量的键.
当你不需要打印时Cache hit!,我会做这样的事情:
def area(length, width)
@cache ||= {}
@cache["#{length},#{width}"] ||= length * width
end
Run Code Online (Sandbox Code Playgroud)
或者,如果你需要一些输出,但a Cache miss!也很好:
def area(length, width)
@cache ||= {}
@cache.fetch("#{length},#{width}") do |key|
puts 'Cache miss!'
@cache[key] = length * width
end
end
Run Code Online (Sandbox Code Playgroud)
如果你想接受更多的参数,你可能想要使用这样的东西:
def area(*args)
@cache ||= {}
@cache[args] ||= args.inject(:*)
end
Run Code Online (Sandbox Code Playgroud)