2012-09-28 72 views
0

一個簡單的問題,但無法弄清楚如何解決它,在Ruby語言缺乏知識:紅寶石輸入輸出問題

 
class Game 
    def initialize 
    get_command 
    end 
    def get_command 
    command = gets 
    puts command    # => POSITION 
    puts command != "POSITION" # => true 
    if command != "POSITION" 
     command = get_command 
    else 
     return true 
    end 
    end 
end 

a = Game.new 

每當我運行一個應用程序,並鍵入POSITION它總是得到true比較"POSITION"任何人都可以解釋爲什麼?

謝謝

回答

2

因爲你實際得到的是「POSITION \ n」。你可以在IRB看到:

command = gets.strip 

command = gets.chomp 

這將去掉空格(包括換行符)關閉輸入:

1.9.3p194 :061 > command = gets 
POSITION 
=> "POSITION\n" 

你應該做比較之前剝去命令。

+1

總是一個好主意來消毒用戶輸入 - 尤其是因爲不同平臺上的行尾字符不同 –