kCC*_*kCC 3 ruby loops while-loop
在Ruby中,循环似乎与彼此完全相同,while和until循环.
使用一个而不是另一个会有什么情况,为什么Ruby有两个似乎做同样事情的循环?
while循环语法如下:
while conditional [do]
code
end
Run Code Online (Sandbox Code Playgroud)
而直到语法:
until conditional [do]
code
end
Run Code Online (Sandbox Code Playgroud)
所以要尽可能清楚:
$i = 0
$num = 5
while $i < $num do
puts("Inside the loop i = #$i" )
$i +=1
end
Run Code Online (Sandbox Code Playgroud)
和
$i = 0
$num = 5
until $i < $num do
puts("Inside the loop i = #$i" )
$i +=1;
end
Run Code Online (Sandbox Code Playgroud)
将产生两个相同的输出:
Inside the loop i = 0
Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
Run Code Online (Sandbox Code Playgroud)
ruby允许多种方式完成相同的事情,因此代码可以自然地读取,具体取决于哪种声音更适合您和您正在编写的代码.有时条件在积极的情况下效果更好,例如something_is_happening?在负面情况下更好something_is_done
并且while在积极的东西继续积极的情况下起作用,而until继续循环直到出现负面的东西.
例如
while 'yes' == keep_going do
keep_going = get_answer
end
Run Code Online (Sandbox Code Playgroud)
VS
until 'stop' == answer do
answer = get_answer
end
Run Code Online (Sandbox Code Playgroud)
另外我注意到你还没有尝试在irb中运行你的两个循环...我知道这是因为第二个的输出肯定与第一个不一样.
2.1.2 :008 > $i = 0
=> 0
2.1.2 :009 > $num = 5
=> 5
2.1.2 :010 >
2.1.2 :011 > until $i < $num do
2.1.2 :012 > puts("Inside the loop i = #$i" )
2.1.2 :013?> $i +=1;
2.1.2 :014 > end
=> nil
Run Code Online (Sandbox Code Playgroud)
这是因为当ruby解释" $i < $num尚未"时,它会评估为true,然后立即停止.