我想返回任何便宜的,它应该返回任何价格低于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 ?
您要找的是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