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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)