[英]Ruby: else without rescue is useless
我是紅寶石的新手。 我正在嘗試編寫一個 apache error.log 監視器。 大部分都完成了,但我收到了警告:否則沒有救援是沒有用的。 我無法弄清楚我做錯了什么。 Ruby 是否希望我使用“除非”?
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
if condition
# …
else
# …
end
不是
if condition
# …
end
else
# …
end
看起來 else 塊不是 if 語句的一部分。 if @@counter > 0
為假,我假設您希望它提供替代路徑if @@counter > 0
正確? 如果是這樣,去掉 else 上面那一行的end
,例如:
if @@Counter > 0
# ... processing ...
else
# ... alternative processing ...
end
澄清: else
警告的目的如下:
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
無論是rescue
被執行,或else
執行,不可能兼顧。
當您有這樣的事情時,也會發生此錯誤:
if condition do
# …
else
# …
end
所以確保你有這樣的東西(刪除保留字“做”)
if condition
# …
else
# …
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.