Ruby:没有救援的其他方面毫无用处

时间:2014-02-16 22:34:02

标签: ruby if-statement

我是红宝石的新手。我正在尝试编写一个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

4 个答案:

答案 0 :(得分:22)

if condition
  # …
else
  # …
end

if condition
  # …
end
else
  # …
end

答案 1 :(得分:2)

看起来else块不是if语句的一部分。假设您希望if @@counter > 0为假时提供替代路径,我是否正确?如果是这样,请摆脱其他地方上方的end,例如:

if @@Counter > 0
    # ... processing ...
else
    # ... alternative processing ...
end

答案 2 :(得分:0)

要澄清:else是警告,其意图如下:

def my_method
  if rand >= 0.5
    raise
  end
rescue
  puts "ERROR!!!"
else
  puts "Cool"
end

如果过早关闭if语句,则在以上代码中,else可能会解释为else。因此,在没有else的情况下使用rescue语句是没有用的,因为您可以像这样简单地编写方法:

def my_method
  if rand >= 0.5
    raise
  end
  puts "Cool"
end

要么执行rescue,要么执行else,但不要同时执行。

答案 3 :(得分:0)

当您遇到类似这样的错误时,也会发生此错误:

if condition do
  # …
else
  # …
end

因此,请确保您有类似这样的内容(不带保留字“ do”)

if condition
  # …
else
  # …
end