Bird
0
0

Which of the following correctly sorts an array employees of hashes by the :salary key using sort_by?

easy📝 Syntax Q3 of 15
Ruby - Enumerable and Collection Processing
Which of the following correctly sorts an array employees of hashes by the :salary key using sort_by?
Aemployees.sort_by { |e| e[:salary].to_s }
Bemployees.sort_by(&:salary)
Cemployees.sort_by { |e| e.salary }
Demployees.sort_by { |e| e[:salary] }
Step-by-Step Solution
Solution:
  1. Step 1: Access hash values correctly

    Hashes use symbol keys accessed with e[:salary].
  2. Step 2: Use sort_by with a block

    The block should return the value to sort by.
  3. Step 3: Evaluate options

    employees.sort_by { |e| e[:salary] } correctly uses e[:salary]. employees.sort_by(&:salary) uses method syntax invalid for hashes. employees.sort_by { |e| e.salary } uses dot notation invalid for hashes. employees.sort_by { |e| e[:salary].to_s } converts salary to string, which changes sorting behavior.
  4. Final Answer:

    employees.sort_by { |e| e[:salary] } -> Option D
  5. Quick Check:

    Hash keys accessed with [:key] in sort_by [OK]
Quick Trick: Use symbol keys with [:key] inside sort_by block [OK]
Common Mistakes:
  • Using dot notation for hash keys
  • Converting numeric keys to strings unnecessarily
  • Using shorthand &:method for hashes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes