Read more

Default Arguments and Memoized

Julian
August 10, 2021Software engineer at makandra GmbH

tl;dr: Avoid to memoize methods with default (keyword) arguments!

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

When you are using Memoized with default arguments or default keyword arguments, there are some edge cased you have to
keep in mind.

When you memoize a method with (keyword) arguments that have an expression as default value, you should be aware
that the expression is evaluated only once.

memoize def print_time(time = Time.now)
  time
end

print_time
=> 2021-07-23 14:23:18 +0200

sleep(1.minute)
print_time
=> 2021-07-23 14:23:18 +0200

When you memoize a method with (keyword) arguments that have default values, you should be aware that Memoized
differentiates between calling the method without any arguments and calling the method with the default values.

memoize def true_or_false(default = true)
  puts 'calculate value ...'
  default
end

true_or_false
calculate value ...
=> true

true_or_false
=> true

true_or_false(true)
calculate value ...
=> true
Posted by Julian to makandra dev (2021-08-10 12:14)