2012-10-10 2 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

은 if 조건이 실행을 계속 끝나면 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

답변을 업데이트했습니다. 이해하는데 도움이되기를 바랍니다. –

관련 문제