我使用Ruby從用戶獲取輸入以爲文件列表提供新名稱。我將這些名稱存儲在一個數組中,但在存儲它之前,我有一系列條件循環來確保用戶的輸入有效。它本質歸結爲這(我已刪除了不相關的問題的部分代碼):循環多個條件,直到滿足所有條件
puts "Rename file to:"
new_name = gets.chomp
new_name = check_input(new_name,@all_names)
@all_names << new_name
def check_input(new_name,all_names)
while new_name.match(/\s/)
puts "Names must not contain spaces:"
new_name = gets.chomp
end
while new_name.empty?
puts "Please enter a name:"
new_name = gets.chomp
end
while all_names.include? new_name
puts "That name already exists. Please enter a different name:"
new_name = gets.chomp
end
return new_name
end
總體而言,這工作得很好,但我想通過每一個「,同時確保循環「情況一次又一次,直到全部的條件得到滿足。如果,例如,一個名爲「ABC」已經存在,用戶按照這個順序:
- 進入「ABC」 =>「這個名字已經存在,請輸入一個不同的 名」
- 進入「ABC 「=>‘的名稱不能包含空格’
- 進入‘ABC’再次=>
中的最後一項工作的成功,但我不希望它,因爲它跳過來檢查的條件重複。是否有更好的方法同時循環這些條件,每個新條目?
謝謝你的幫助!
精美高效。非常感謝! – lumos