RUBY while & until loop zero or more , one or more times

简介:
RUBY 中while和until用来写循环时, 需要注意有几种写法. 
其中使用begin和end的写法是先执行循环体再判断条件的, 因此循环体至少被执行1次.
其他写法是先判断条件, 再执行循环体, 因此循环体可能执行0次或多次. 

例如 :
def tried
 return false
end

while tried do puts("a") end    # a single-line while loop

while tried             # a multiline while loop
    puts("b")
end

puts("c") while tried        # single-line while modifier

begin                 # multiline while modifier
    puts("d")
end while tried


结果输出"d", 说明了问题.

until 也一样 : 
如下 :
def tried
 return true
end

until tried do puts("a") end    # a single-line while loop

until tried             # a multiline while loop
    puts("b")
end

puts("c") until tried        # single-line while modifier

begin                 # multiline while modifier
    puts("d")
end until tried


相关文章
|
5月前
|
Python
Python time sleep()方法
t – 推迟执行的秒数。 返回值 该函数没有返回值。
59 0
|
3月前
|
Python
python tkinter Tcl_AsyncDelete: async handler deleted by the wrong thread
python tkinter Tcl_AsyncDelete: async handler deleted by the wrong thread
39 1
|
28天前
|
Python
gyp ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.
gyp ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.
25 1
|
Python
Python 3.5 RuntimeError: can't start new thread
/*********************************************************************** * Python 3.5 RuntimeError: can't start new thread * 说明: * 测试的时候线程开得太多了,导致软件开始,不再能够被处理,卡死。
6022 0
|
9月前
|
存储 Shell Python
Python中os.system()、subprocess.run()、call()、check_output()的用法
Python中os.system()、subprocess.run()、call()、check_output()的用法
183 0
|
9月前
|
缓存 监控 架构师
Go 函数式编程:Higher-order function
Go 函数式编程:Higher-order function
103 0
|
10月前
|
Python
Python中eval与exec的使用及区别
Python中eval与exec的使用及区别
|
11月前
|
Python
Python built-in module time 内建时间库常用函数
Python built-in module time 内建时间库常用函数
86 0
成功解决ERROR: Command errored out with exit status 1: command: 'f:\program files\python\python36\pyt
成功解决ERROR: Command errored out with exit status 1: command: 'f:\program files\python\python36\pyt
(Python)asyncio使用异常:This event loop is already running解决方式
(Python)asyncio使用异常:This event loop is already running解决方式