是否可以告诉 ruby 只发出一次警告,而不是多次发出警告?
class SoylentGreen
def eat
warn "Algae harvesting not implemented. Soylent green is people!"
end
end
5.times do
soylent_green = SoylentGreen.new
soylent_green.eat
end
产生
Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
Algae harvesting not implemented. Soylent green is people!
而理想情况下,我希望它只发生一次。
我没有使用 Rails,但可以访问 ruby 1.8 和 1.9。
备选方案包括编写我自己的警告系统(它只涵盖像这样的故意警告),或者将警告放在 SoylentGreen#eat
之外(这会导致它显示,即使该方法未被调用)。
最佳答案
基于混沌的回答..
class SoylentGreen
def eat
warn_once "Algae harvesting not implemented. Soylent green is people!"
end
def warn_once(msg)
@@warned||=false
if not @@warned then
@@warned = true
warn msg
end
end
end
关于ruby - 如何在 ruby 中只发出一次警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2376184/