首页 > 解决方案 > 退回任何价值低于 300 美元的 Ruby Hash 商品

问题描述

我想退回任何便宜的物品,应该退回任何价格低于 300 美元的物品。

这是主要课程;

class ShoesInventory
  def initialize(items)
    @items = items
  end

  def cheap
    # this is my solution, but it just print out an array of boolean
    @items.map { |item| item[:price] < 30 }

    # to be implemented
  end
end

这是类的一个实例;

ShoesInventory.new([
  {price: 101.00, name: "Nike Air Force 1 Low"}},
  {price: 232.00, name: "Jordan 4 Retro"},
  {price: 230.99, name: "adidas Yeezy Boost 350 V2"},
  {price: 728.00, name: "Nike Dunk Low"}
]).cheap

我希望结果是这样的;

# => [
#      {price: 101.00, name: "Nike Air Force 1 Low"}},
#      {price: 232.00, name: "Jordan 4 Retro"},
#      {price: 230.99, name: "adidas Yeezy Boost 350 V2"},
#    ]

Can you guide me ?

标签: arraysrubyinventory-managementruby-hash

解决方案


您正在寻找的是Enumerable#select.

class ShoesInventory
  def initialize(items)
    @items = items
  end

  def cheap
    @items.select { |item| item[:price] < 30 }
  end
end

如果您希望能够链接方法,您可能还希望返回一个新的清单实例:

def cheap
  self.class.new(@items.select { |item| item[:price] < 30 })
end

推荐阅读