Bird
0
0

Why does sort_by often perform faster than sort with a block for complex sorting?

hard📝 Conceptual Q10 of 15
Ruby - Enumerable and Collection Processing
Why does sort_by often perform faster than sort with a block for complex sorting?
ABecause <code>sort_by</code> only works on numbers
BBecause <code>sort_by</code> computes keys once before sorting
CBecause <code>sort_by</code> modifies the original array in place
DBecause <code>sort_by</code> uses parallel processing internally
Step-by-Step Solution
Solution:
  1. Step 1: Understand how sort_by works internally

    sort_by creates an array of keys by applying the block once per element.
  2. Step 2: Compare with sort with block

    sort with block compares elements multiple times, recalculating keys repeatedly.
  3. Final Answer:

    Because sort_by computes keys once before sorting -> Option B
  4. Quick Check:

    Key computation optimization = Because sort_by computes keys once before sorting [OK]
Quick Trick: sort_by caches keys, making sorting faster for complex keys [OK]
Common Mistakes:
  • Thinking it uses parallelism
  • Assuming it sorts in place
  • Believing it only works on numbers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes