Bird
0
0

How can you group a list of products by category and then by price range (cheap: group_by calls?

hard📝 Application Q9 of 15
Ruby - Enumerable and Collection Processing
How can you group a list of products by category and then by price range (cheap: <50, expensive: ≥50) using nested group_by calls?
products = [{name: 'Pen', category: 'Stationery', price: 10}, {name: 'Notebook', category: 'Stationery', price: 60}, {name: 'Mug', category: 'Kitchen', price: 40}]
Aproducts.group_by { |p| p[:category] }.transform_values { |arr| arr.group_by { |p| p[:price] < 50 ? :cheap : :expensive } }
Bproducts.group_by { |p| p[:price] < 50 ? :cheap : :expensive }.group_by { |p| p[:category] }
Cproducts.group_by { |p| [p[:category], p[:price] < 50 ? :cheap : :expensive] }
Dproducts.group_by { |p| p[:category] + p[:price].to_s }
Step-by-Step Solution
Solution:
  1. Step 1: Group products by category

    Use group_by on category to get a hash with categories as keys.
  2. Step 2: For each category group, group by price range

    Use transform_values to apply group_by again on price range within each category array.
  3. Step 3: Check options

    products.group_by { |p| p[:category] }.transform_values { |arr| arr.group_by { |p| p[:price] < 50 ? :cheap : :expensive } } correctly nests group_by calls. products.group_by { |p| p[:price] < 50 ? :cheap : :expensive }.group_by { |p| p[:category] } incorrectly chains group_by on the whole array twice. products.group_by { |p| [p[:category], p[:price] < 50 ? :cheap : :expensive] } groups by combined array key, not nested. products.group_by { |p| p[:category] + p[:price].to_s } concatenates strings, not grouping properly.
  4. Final Answer:

    products.group_by { |p| p[:category] }.transform_values { |arr| arr.group_by { |p| p[:price] < 50 ? :cheap : :expensive } } -> Option A
  5. Quick Check:

    Use transform_values for nested group_by [OK]
Quick Trick: Use transform_values to apply group_by on nested groups [OK]
Common Mistakes:
  • Chaining group_by incorrectly
  • Using combined keys instead of nested hashes
  • Concatenating strings instead of grouping

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes