Bird
0
0

How can you safely chain methods when some may return nil?

hard📝 Application Q9 of 15
Ruby - Functional Patterns in Ruby
How can you safely chain methods when some may return nil?
Example:
user&.profile&.address&.city
What does this pattern prevent?
AIt prevents NoMethodError by stopping chain if nil encountered
BIt forces all methods to return strings
CIt automatically retries methods on failure
DIt converts nil to empty string before chaining
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe navigation operator (&.)

    The &. operator calls method only if object is not nil, else returns nil immediately.
  2. Step 2: Identify error prevention

    This prevents NoMethodError when chaining methods on possible nil objects.
  3. Final Answer:

    It prevents NoMethodError by stopping chain if nil encountered -> Option A
  4. Quick Check:

    Safe navigation avoids errors on nil in chains [OK]
Quick Trick: Use &. to safely chain methods on possible nil objects [OK]
Common Mistakes:
  • Thinking it forces return types
  • Assuming it retries failed calls
  • Believing it converts nil to string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes