Ruby中`until`和`until do`循环的区别是什么?

时间:2015-05-27 14:21:08

标签: ruby loops

c = 5
until c == 0 do
  print c
  c -= 1
end

/断

c = 5
until c == 0 
  print c
  c -= 1
end

区别是什么? 它们都显示54321作为输出。

3 个答案:

答案 0 :(得分:2)

do是可选的。它表示要重复执行的代码块的开始。

在你的例子中没有区别。但是,如果您尝试在一行中重写代码,您可以看到它所需的原因:

c = 5
until c == 0 do print c; c -= 1 end
# 54321 => nil

现在尝试不使用do

c = 5
until c == 0 print c; c -= 1 end
# SyntaxError: (irb):115: syntax error, unexpected tIDENTIFIER, expecting keyword_do_cond or ';' or '\n'

正如您所看到的,没有明确的阻止开头,Ruby将抛出SyntaxError

答案 1 :(得分:0)

绝对没有区别。它就像onSelect : function (oEvent) { 'use strict'; console.log("onSelect"); } vs while [condition] [block] endwhile [condition] do [block] end vs if [condition] [block] end

在Ruby中,通常有很多方法可以做同样的事情 - 重要的是要保持一致,无论哪种方式。

答案 2 :(得分:0)

MinVersionuntil之间没有区别。 until do是可选的,两者都会显示相同的输出。如果想更多地了解这个while and while do