Ruby 鲁比:否则没有救援就没用了
我对ruby不熟悉。我正在尝试编写一个apache error.log监视器。这件事基本上已经完成了,但我得到了警告:否则没有救援是没有用的。 我不知道我做错了什么。Ruby希望我使用“除非”吗Ruby 鲁比:否则没有救援就没用了,ruby,if-statement,Ruby,If Statement,我对ruby不熟悉。我正在尝试编写一个apache error.log监视器。这件事基本上已经完成了,但我得到了警告:否则没有救援是没有用的。 我不知道我做错了什么。Ruby希望我使用“除非”吗 class ErrorMonitor @@previous_size=0 @@counter=0 def initialize() end def process if @@counter > 0 @new_size= File.stat('
class ErrorMonitor
@@previous_size=0
@@counter=0
def initialize()
end
def process
if @@counter > 0
@new_size= File.stat('/var/log/apache2/error.log').size
if @new_size > @@previous_size
for i in @@previous_size..@new_size - @@previous_size
print IO.readlines("/var/log/apache2/error.log")[i]
end
@@previous_size = @new_size
end
end
else
@@previous_size= File.stat('/var/log/apache2/error.log').size
@@counter=1;
end # <- this line is where the warning points to
end
# main execution
em = ErrorMonitor.new()
while true
em.process
sleep 10
end
类错误监视器
@@以前的大小=0
@@计数器=0
def初始化()
结束
def过程
如果@@计数器>0
@new_size=File.stat('/var/log/apache2/error.log').size
如果@new\u size>@@previous\u size
对于@@previous\u size..@new\u size-@@previous\u size中的i
打印IO.readlines(“/var/log/apache2/error.log”)[i]
结束
@@以前的大小=@新大小
结束
结束
其他的
@@previous_size=File.stat('/var/log/apache2/error.log').size
@@计数器=1;
完#
不是
看起来else块不是if语句的一部分。当如果@counter>0
为false时,我是否正确地假设您希望它提供一个替代路径?如果是这样,请去掉位于else上方的结尾
,例如:
if @@Counter > 0
# ... processing ...
else
# ... alternative processing ...
end
要澄清:否则
警告的目的如下:
def my_method
if rand >= 0.5
raise
end
rescue
puts "ERROR!!!"
else
puts "Cool"
end
如果过早关闭If
语句,则else
可能会被解释为上述代码中的else
。因此,没有rescue
的else
语句是没有用的,因为您可以这样简单地编写您的方法:
def my_method
if rand >= 0.5
raise
end
puts "Cool"
end
if condition do
# …
else
# …
end
要么执行rescue
,要么执行else
,永远不要同时执行两者。当您遇到以下情况时,也会发生此错误:
def my_method
if rand >= 0.5
raise
end
puts "Cool"
end
if condition do
# …
else
# …
end
因此,请确保您有类似的内容(删除保留字“do”)
当前@@counter
是一个int,但您将其用作布尔值。同样,如果您只有一个ErrorMonitor对象,则不需要@
类变量修饰符--@计数器
,@previous\u size
。同样地,@new\u size
也不需要持久化,因此new\u size
可以工作。
if condition
# …
else
# …
end