我有一组Mortgage对象
class Mortgage
attr_accessor :rate, :deposit
def initialize(deposit, rate)
@deposit = deposit
@rate = rate
end
end
我想拒绝任何抵押贷款的比率高于另一笔抵押贷款的抵押贷款。
例如,想象一下以下抵押贷款数组
Mortgage 1, :rate => 3, :deposit => 20
Mortgage 2, :rate => 5, :deposit => 20
Mortgage 3, :rate => 7, :deposit => 30
该方法应拒绝抵押2。
答案 0 :(得分:5)
mortgages = [
Mortgage.new(20, 3),
Mortgage.new(20, 5),
Mortgage.new(30, 7)
]
mortgages.group_by(&:deposit).map { |deposit, mortgages| mortgages.min_by(&:rate) }
group_by
根据给定的方法构造一个哈希值,因此在这种情况下它给出:
{
20 => [
#<Mortgage:0x24 @rate=3 @deposit=20>,
#<Mortgage:0x2c @rate=5 @deposit=20>
],
30 => [
#<Mortgage:0x38 @rate=7 @deposit=30>
]
}
然后,只需按每笔存款的最低费率抵押即可。