2016-12-05 17 views
-1

我想創建一個用戶定義的錯誤,如果用戶只輸入他們的名字,它會引發一個錯誤,並告訴用戶再次嘗試或,如果他們輸入一個數字,會引發錯誤。如何從用戶輸入在Ruby中創建用戶定義的異常

這是我的代碼,但是當我運行它輸出「輸入你的名字和姓氏」,那麼無論我輸入一個完整的名字,它都可以解救它。它仍然說「對不起,我沒有抓到。」那麼串接它:

class MyNewException < Exception 
    attr_reader :first, :last 

    def initialize(first) 
    @first = first 
    end 
end 

print "Enter your first and last name: " 

begin 

first = gets.chomp 
last = gets.chomp 

#prompt the user to enter first and last name 
rescue MyNewException 
    puts "Sorry I didn't quite catch that. Try again." 
    gets 
else 
    puts "Hello, " + first + last + "!" 
end 
+1

當我將代碼複製到irb中時,它對我有用。 –

+0

我無法重現您的問題。 –

回答

0

gets會搶你按下回車鍵入的所有內容。因此first實際上包含您輸入的名字和姓氏,然後last爲空。它看起來像是連接在一起,但所有的文本都在first。如果你輸入你的名字,然後按輸入,然後輸入你的第二個名字,那麼它應該輸出這兩個名字。

錯誤沒有被提出。如果你想在最後一個空白時提出錯誤,你需要添加這樣的內容:

last = gets.chomp 
if last == "" 
    raise MyNewException, first 
end