-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
當我將代碼複製到irb中時,它對我有用。 –
我無法重現您的問題。 –