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
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 lessonsWhat ||= does
How x ||= value expands to x || (x = value) and works on unassigned locals and instance variables.
||= for default values
Uses of ||= in this app's partials and helpers that supply default values without caching anything on an object.
Memoization: caching the first call
Memoization stores an expensive result in an instance variable, and a call counter shows it runs once.
The false/nil memoization trap
Why @value ||= false recomputes on every call, since false is falsy and ||= only checks truthiness.
The defined? fix
Using defined?(@ivar) to check whether a variable was assigned, so false and nil values stay memoized.
When to memoize, and when not to
When memoization costs more than it saves, how cached values go stale, and a three-question checklist.
Putting memoization together
A review of the whole course, from the ||= expansion to the defined? fix and the limits of memoization.