我正在使用以下代碼讓用戶輸入名稱,而程序將它們存儲在數組中,直到他們輸入一個空字符串(他們必須在每個名稱之后按Enter):people = []info = 'a' # must fill variable with something, otherwise loop won't executewhile not info.empty? info = gets.chomp people += [Person.new(info)] if not info.empty?end這段代碼在do ... while循環中看起來會更好:people = []do info = gets.chomp people += [Person.new(info)] if not info.empty?while not info.empty?在此代碼中,我不必將信息分配給一些隨機字符串。不幸的是,Ruby中似乎不存在這種類型的循環。有人可以建議一種更好的方法嗎?
3 回答

眼眸繁星
TA貢獻1873條經驗 獲得超9個贊
注意:
該begin <code> end while <condition>由Ruby的作者Matz的拒絕。相反,他建議使用Kernel#loop,例如
loop do
# some code here
break if <condition>
end
這是2005年11月23日的電子郵件交流,其中Matz說:
|> Don't use it please. I'm regretting this feature, and I'd like to
|> remove it in the future if it's possible.
|
|I'm surprised. What do you regret about it?
Because it's hard for users to tell
begin <code> end while <cond>
works differently from
<code> while <cond>
RosettaCode Wiki具有類似的故事:
在2005年11月,Ruby的創建者Matsuki Yukihiro Matsumoto對這個循環功能感到遺憾,并建議使用Kernel#loop。
- 3 回答
- 0 關注
- 739 瀏覽
添加回答
舉報
0/150
提交
取消