2012-10-10 151 views
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,但似乎也沒有做太多。它甚至如何存儲多個變量?

回答

2

的HitsPerMinute方法被調用幾次,當如果條件結束繼續運行,做一個循環,而不是

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 
+0

我不得不問,它是如何存儲多個變量的?它沒有被設置爲一個數組,如果將它們存儲爲'\ n d \ n13',我會感到非常驚訝。 – SecurityGate

+0

我更新了答案,希望它有助於理解它 –