这是使用while
的代码:
i = 0
num = 5
while i < num do
puts "Inside the loop! i = #{i}"
i += 1
end
这是使用until
的代码:
i = 0
num = 5
until i > num do
puts "Inside the loop! i = #{i}"
i += 1
end
有人可以给一个时,应首选,而不是其他的例子吗?对我来说,没有理由有until
,如果他们做同样的事情while
。在我看来,这就是为什么其他编程语言不具备这两个原因。
这是关于可读性。一个“正确”的例子完全是主观的:
done = my_function until done
要么
done = false
until done
# better than "while not done"? Who can say?
# do something that modifies the state of done
end
要么
my_object.do_something until my_object.complete
# Or, if the method were otherwise named...
my_object.do_something while my_object.incomplete
哪个更好:
makeSoup while !ingredients.empty?
makeSoup until ingredients.empty?
while
和until
做同样的事情,一个就是“更好的”阅读在某些情况下。