Bird
0
0

Which of these is a valid way to use sort_by to sort an array of numbers nums by their absolute value?

easy📝 Conceptual Q2 of 15
Ruby - Enumerable and Collection Processing
Which of these is a valid way to use sort_by to sort an array of numbers nums by their absolute value?
Anums.sort_by { |n| n.absolute }
Bnums.sort_by { |n| n.abs }
Cnums.sort_by { |n| abs(n) }
Dnums.sort_by.abs { |n| n }
Step-by-Step Solution
Solution:
  1. Step 1: Recall Ruby syntax for sort_by with block

    The block should take each element and return the value to sort by, here n.abs.
  2. Step 2: Check method usage correctness

    abs is a method on numbers, so n.abs is correct. Other options misuse syntax or method names.
  3. Final Answer:

    nums.sort_by { |n| n.abs } -> Option B
  4. Quick Check:

    Correct block syntax = nums.sort_by { |n| n.abs } [OK]
Quick Trick: Use element.method inside block for sorting [OK]
Common Mistakes:
  • Using wrong method call syntax
  • Calling abs as a standalone function
  • Using non-existent methods like absolute

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes