为了账号安全,请及时绑定邮箱和手机立即绑定

Ruby中是否有“ do…while”循环?

Ruby中是否有“ do…while”循环?

手掌心 2019-11-21 15:12:17
我正在使用以下代码让用户输入名称,而程序将它们存储在数组中,直到他们输入一个空字符串(他们必须在每个名称之后按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。


查看完整回答
反对 回复 2019-11-21
  • 3 回答
  • 0 关注
  • 656 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信