Bird
0
0

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:
  1. Step 1: Understand memoization and purity

    Memoization caches results but must not cause side effects or depend on external state.
  2. 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.
  3. Final Answer:

    Store results in a local hash passed as an argument. -> Option B
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes