2013-10-06 26 views

回答

2

你錯過了方法String#chomp。如下更改代碼:

print "Enter a character " 
a = gets.chomp 
if (a == "b") 
    puts "b was pressed" 
end 

現在運行代碼:

[email protected]:~/Ruby$ ruby so.rb 
Enter a character b 
b was pressed 
[email protected]:~/Ruby$ 

注:您的代碼不能正常工作,因爲a = gets實際上是分配"b\n"給變量a,這當然不等於"b"。但是使用#chomp會從字符串中刪除\n,您只需從命令提示符輸入並且會產生預期的輸出。

相關問題