我有一个默认值为0的哈希: Hash.new(0)
假设一个整数值,有没有办法设置'floor',这样如果该值低于楼层,那么该楼层会被返回?
例:
h = Hash.new(0)
h.floor = 0
h[:five] += 5
h[:five]
#=> 5
h[:negative_five] -= 5
h[:negative_five]
#=> 0
Run Code Online (Sandbox Code Playgroud)
这是一个可能的实现
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |