0

在我慢慢编写日志记录脚本时,我遇到了一些障碍。我已经完成了大部分程序的工作,但现在我只是添加了一些物质享受,例如对你可以输入的内容的一些限制等等。

def HitsPerMinute()

print "Is there a specific hour you would like to see: "
STDOUT.flush
mhour = spectime = gets.strip

 #mhour = mhour.to_s
 if mhour == '' or mhour == '\n' or (mhour =~ /[a-z]|[A-Z].*/)
   puts "Please enter an hour you would like to see."
   HitsPerMinute()
 #else
   #mhour = mhour.to_i
  end
    mstart = 00
    mend = 59

    mstart.upto(mend) { |x|
     moment = "#{rightnow}:#{zeroadder(mhour)}:#{zeroadder(x)}".strip
     print "Server hits at '#{moment}: "
     puts `cat /home/*/var/*/logs/transfer.log | grep -c #{moment}`
      x = x.to_i
      x = x.next
     }
 end

HitsPerMinute()

在大多数情况下,它工作得很好,除了它似乎存储了之前输入的变量。如此处所示。

Is there a specific hour you would like to see:  
Please enter an hour you would like to see.
Is there a specific hour you would like to see:  
Please enter an hour you would like to see.
Is there a specific hour you would like to see: d
Please enter an hour you would like to see.
Is there a specific hour you would like to see: 13
Server hits at '10/Oct/2012:13:00: 48
[...]
Server hits at '10/Oct/2012:13:59: 187
Server hits at '10/Oct/2012:0d:00: 0
Server hits at '10/Oct/2012:0d:01: 0
[...]
Server hits at '10/Oct/2012:0d:57: 0
Server hits at '10/Oct/2012:0d:58: 0
Server hits at '10/Oct/2012:0d:59: 0
Server hits at '10/Oct/2012::00: 0
Server hits at '10/Oct/2012::01: 0
[...]

我在输入变量上使用 .strip ,但这似乎对这个问题没有任何作用。我尝试使用 .flush ,但这似乎也没有多大作用。它甚至如何存储多个变量?

4

1 回答 1

2

HitsPerMinute 方法被多次调用,当 if 条件结束时它会继续运行,而是在循环中执行

def HitsPerMinute()

  STDOUT.flush
  mhour = ''

  while mhour == '' or mhour == '\n' or (mhour =~ /[a-z]|[A-Z].*/) do
    puts "Please enter an hour you would like to see."
    mhour = spectime = gets.strip
  end

  mstart = 00
  mend = 59

  mstart.upto(mend) { |x|
    moment = "#{rightnow}:#{zeroadder(mhour)}:#{zeroadder(x)}".strip
    print "Server hits at '#{moment}: "
    puts `cat /home/*/var/*/logs/transfer.log | grep -c #{moment}`
    x = x.to_i
    x = x.next
  }
end

HitsPerMinute()
  • 关于变量的更新:

它没有在 mhour 变量上存储多个值,每次调用该方法时 mhour 只有一个值。用户在方法结束之前被回答输入一个新值,所以当它最终结束时,之前的调用会继续运行,也许这个例子有助于理解:

def method(i)
  if i < 5
    method(i+1)
  end
  puts i
end

method(1)

输出:

$ ruby /tmp/test.rb
5
4
3
2
1
于 2012-10-10T20:36:39.847 回答