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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)