红宝石 - 为什么要使用“直到”时“而”可以做同样的[关闭]

问题描述 投票:5回答:2

这是使用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。在我看来,这就是为什么其他编程语言不具备这两个原因。

ruby
2个回答
11
投票

这是关于可读性。一个“正确”的例子完全是主观的:

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

15
投票

哪个更好:

  1. makeSoup while !ingredients.empty?
  2. makeSoup until ingredients.empty?

whileuntil做同样的事情,一个就是“更好的”阅读在某些情况下。

© www.soinside.com 2019 - 2024. All rights reserved.