arrays - 退回任何价值低于 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 ?
解决方案
您正在寻找的是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
推荐阅读
- django - 我是否应该始终信任 Django 中的 W0613 pylint 警告,尤其是对于以 **kwargs 作为参数的函数?
- c - 如何修复 C 函数给出错误的总和值
- python - 如何将 Google-Cloud-Vision OCR protobuf 响应保存/加载到磁盘?
- python - 如何让我的 Django 查询只返回平均值和另一列?
- java - 从另一个类获取列表数组中的帖子数。但它不起作用?
- mysql - 在 where 中使用时间戳和在有子句中的计数
- javascript - 使用 Mocha 测试 ES 2015 模块
- c++ - 两种类型的定义构造函数有什么区别?第一个使用“:”,第二个在花括号中定义它,如函数
- gdb - GDB 能够改变(JLE 到 JGE)吗?
- angular - 登录方法后如何获取Web令牌的访问权限