Bird
0
0

Which of the following is a valid way to group an array nums by whether elements are positive or negative using group_by returning :positive or :negative?

easy📝 Conceptual Q2 of 15
Ruby - Enumerable and Collection Processing
Which of the following is a valid way to group an array nums by whether elements are positive or negative using group_by returning :positive or :negative?
Anums.group_by { |n| n > 0 ? :positive : :negative }
Bnums.group_by(&:positive?)
Cnums.group_by { |n| n if n > 0 }
Dnums.group_by { |n| n > 0 }
Step-by-Step Solution
Solution:
  1. Step 1: Understand grouping by condition

    We want to group by positive or negative, so the block should return a symbol or label for each element.
  2. Step 2: Check each option's block return value

    nums.group_by { |n| n > 0 ? :positive : :negative } returns :positive or :negative explicitly, which is clear and correct. nums.group_by(&:positive?) calls a method that returns true/false but does not distinguish negative. nums.group_by { |n| n if n > 0 } returns nil for negatives, which is not a proper group key. nums.group_by { |n| n > 0 } returns true/false but does not label groups clearly.
  3. Final Answer:

    nums.group_by { |n| n > 0 ? :positive : :negative } -> Option A
  4. Quick Check:

    group_by block returns clear group keys = nums.group_by { |n| n > 0 ? :positive : :negative } [OK]
Quick Trick: Use clear labels in group_by block for distinct groups [OK]
Common Mistakes:
  • Returning nil in block
  • Using methods that don't distinguish groups
  • Returning boolean without labels

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes