我有很多抵押物
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。
最佳答案
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>
]
}
那么就很容易从每一笔存款中提取最低利率的抵押贷款。