Ruby中有“do ... while”循环吗?

我正在使用此代码让用户输入名称,而程序将它们存储在一个数组中,直到它们输入一个空字符串(他们必须在每一个名称后按Enter键): web

people = []
info = 'a' # must fill variable with something, otherwise loop won't execute

while 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

不幸的是,Ruby中彷佛不存在这种类型的循环。 任何人均可以建议一个更好的方法吗? jsp


#1楼

当心oop

begin <code> end while <condition>被Ruby的做者Matz拒绝。 相反,他建议使用Kernel#loop ,例如 网站

loop do 
  # some code here
  break if <condition>
end

这是2005年11月23日的电子邮件交换 ,Matz声明: this

|> 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有相似的故事: spa

2005年11月,Ruby的建立者Yukihiro Matsumoto对这个循环功能表示遗憾并建议使用Kernel#loop。 code


#2楼

我在Ruby核心库中读取Tempfile#initialize的源代码时发现了如下片断: rem

begin tmpname = File.join(tmpdir, make_tmpname(basename, n)) lock = tmpname + '.lock' n += 1 end while @@cleanlist.include?(tmpname) or File.exist?(lock) or File.exist?(tmpname)

乍一看,我假设while修饰符将在begin ... end的内容以前进行评估,但事实并不是如此。 注意:

>> begin ?> puts "do {} while ()" >> end while false do {} while () => nil

正如您所料,循环将在修饰符为true时继续执行。

>> n = 3 => 3 >> begin ?> puts n >> n -= 1 >> end while n > 0 3 2 1 => nil

虽然我很高兴再也看不到这个成语,但开始......结束是很是强大的。 如下是记忆没有参数的单线方法的经常使用习语:

def expensive @expensive ||= 2 + 2 end

这是一个丑陋但快速的方法来记忆更复杂的东西:

def expensive @expensive ||= begin n = 99 buf = "" begin buf << "#{n} bottles of beer on the wall\\n" # ... n -= 1 end while n > 0 buf << "no more bottles of beer" end end

最初由Jeremy Voorhis编写。 内容已在此处复制,由于它彷佛已从原始网站中删除。 副本也能够在Web ArchiveRuby Buzz论坛中找到 - 蜥蜴


#3楼

像这样:

people = []

begin
  info = gets.chomp
  people += [Person.new(info)] if not info.empty?
end while not info.empty?

参考: Ruby的Hidden do {} while()循环


#4楼

这个怎么样?

people = []

until (info = gets.chomp).empty?
  people += [Person.new(info)]
end

#5楼

这如今正常工做:

begin
    # statment
end until <condition>

可是,它可能在未来被删除,由于begin语句是违反直觉的。 见: http//blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745

Matz(Ruby的建立者)建议这样作:

loop do
    # ...
    break if <condition>
end
相关文章
相关标签/搜索