Junior Track Roadmap

Ruby idioms: memoization

This course covers Ruby's ||= operator and how it supports memoization. It starts with how x ||= value expands to x || (x = value) and why it works on a variable that was never assigned. It separates default values in Rails partials and helpers from caching a result on an object. Call counters show memoization running an expensive step once. The course then shows why ||= cannot memoize false or nil, fixes this with defined?, and ends with cases where memoization adds complexity or stale data.

What you'll learn

  • ✓How x ||= value expands to x || (x = value) and works on unassigned variables
  • ✓How ||= for default values differs from memoization
  • ✓Caching an expensive result in an instance variable with @ivar ||=
  • ✓Why @value ||= false recomputes on every call
  • ✓Using defined?(@ivar) to memoize values that can be false or nil
  • ✓When memoization is not worth it and how cached values go stale
Free preview · Lesson 1 3 min read

What ||= does

||= looks like its own syntax, but it combines two things from earlier courses: || (short-circuit OR) and = (assignment). x ||= 5 works like this:

Read the full lesson free →

Curriculum

7 lessons
Type to start searching...