How does memoization work in Ruby, and what does the ||= operator do?

Last updated 27 June 2026

  • Memoization caches an expensive result so it is computed once, typically via @value ||= compute.

  • a ||= b means a || (a = b): it assigns only when a is nil or false.

  • If the real result is nil or false, it recomputes every call. Guard with defined?(@value) instead.

  • https://thoughtbot.com/blog/ruby-memoization-and-alternatives
  • https://www.reddit.com/r/ruby/comments/ukyrr9/ruby_memoization_what_it_is_when_to_use_it_what/
  • https://medium.com/@kklimuk/memoization-in-ruby-made-easy-a4b0f6c11846
  • https://dev.to/baweaver/understanding-ruby-memoization-2be5
  • https://medium.com/@kanhu.dubey9/understanding-memoization-in-ruby-boosting-performance-with-simple-techniques-190dd63de513
  • https://www.railscarma.com/blog/a-guide-to-memoization-in-ruby/
All Ruby interview questions