I'm wondering if there is a more "Ruby-like" way to memoize functions with multiple parameters in Ruby. Here's a way that I came up with that works but not sure if it's the best approach:
@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
The parameters are joined with a comma which is then used as a key for storage in the @cache
variable.