How can you combine pure functions with memoization in Ruby without breaking purity?
hard📝 Application Q9 of 15
Ruby - Functional Patterns in Ruby
How can you combine pure functions with memoization in Ruby without breaking purity?
APrint cached results to console.
BStore results in a local hash passed as an argument.
CModify instance variables to save results.
DUse a global variable to cache results.
Step-by-Step Solution
Solution:
Step 1: Understand memoization and purity
Memoization caches results but must not cause side effects or depend on external state.
Step 2: Evaluate options
Store results in a local hash passed as an argument. uses local hash passed in, keeping function pure. Options B and C modify external state. Print cached results to console. causes side effect by printing.
Final Answer:
Store results in a local hash passed as an argument. -> Option B
Quick Check:
Memoization with local state keeps purity [OK]
Quick Trick:Pass cache as argument to keep function pure [OK]
Common Mistakes:
Using global or instance variables for cache
Printing inside memoized function
Ignoring side effects in caching
Master "Functional Patterns in Ruby" in Ruby
9 interactive learning modes - each teaches the same concept differently