gpt4 book ai didi

ruby - 散列的'floor'值?

转载 作者:数据小太阳 更新时间:2023-10-29 08:18:17 25 4
gpt4 key购买 nike

我有一个默认值为 0 的散列:Hash.new(0)

假设一个整数值,有没有办法设置一个“floor”,这样如果该值低于该 floor,则该 floor 被返回?

例子:

h = Hash.new(0)
h.floor = 0

h[:five] += 5
h[:five]
#=> 5

h[:negative_five] -= 5
h[:negative_five]
#=> 0

最佳答案

这是一个可能的实现

class MyHash < Hash
attr_writer :floor

def [](key)
# you can use one of those two lines or your own code in case the floor hasn't been define
# raise 'floor value must be defined' if @floor.nil?
# super key if @floor.nil?
value = (fetch(key) < @floor ? @floor : fetch(key))
end
end

关于ruby - 散列的'floor'值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com