Bird
0
0

Given an array of hashes representing products:

hard📝 Application Q15 of 15
Ruby - Enumerable and Collection Processing
Given an array of hashes representing products:
products = [
  {name: "Pen", price: 1.5, stock: 10},
  {name: "Notebook", price: 2.0, stock: 0},
  {name: "Eraser", price: 0.5, stock: 5}
]
How would you use sort_by to get products sorted by price but only include those with stock greater than zero?
Aproducts.sort_by { |p| p[:stock] }.select { |p| p[:price] > 0 }
Bproducts.sort_by { |p| p[:price] if p[:stock] > 0 }
Cproducts.sort_by { |p| p[:stock] > 0 ? p[:price] : 0 }
Dproducts.select { |p| p[:stock] > 0 }.sort_by { |p| p[:price] }
Step-by-Step Solution
Solution:
  1. Step 1: Filter products with stock > 0

    Use select to keep only products where stock is greater than zero.
  2. Step 2: Sort filtered products by price

    Apply sort_by on the filtered array to sort by price.
  3. Final Answer:

    products.select { |p| p[:stock] > 0 }.sort_by { |p| p[:price] } -> Option D
  4. Quick Check:

    Filter then sort_by for correct result [OK]
Quick Trick: Filter first, then sort_by for combined conditions [OK]
Common Mistakes:
  • Trying to filter inside sort_by block
  • Sorting by stock instead of price
  • Selecting after sorting, which keeps unwanted items

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes