我使用这段代码让用户输入名称,而程序将它们存储在一个数组中,直到他们输入一个空字符串(他们必须在每个名称后按enter):
people = []
info = 'a' # must fill variable with something, otherwise loop won't execute
while not info.empty?
info = gets.chomp
people += [Person.new(info)] if not info.empty?
end
这段代码在do…while循环:
people = []
do
info = gets.chomp
people += [Person.new(info)] if not info.empty?
while not info.empty?
在这段代码中,我不需要将信息分配给一些随机字符串。
不幸的是,Ruby中似乎不存在这种类型的循环。谁能提出一个更好的方法来做这件事?
I found the following snippet while reading the source for Tempfile#initialize in the Ruby core library:
begin
tmpname = File.join(tmpdir, make_tmpname(basename, n))
lock = tmpname + '.lock'
n += 1
end while @@cleanlist.include?(tmpname) or
File.exist?(lock) or File.exist?(tmpname)
At first glance, I assumed the while modifier would be evaluated before the contents of begin...end, but that is not the case. Observe:
>> begin
?> puts "do {} while ()"
>> end while false
do {} while ()
=> nil
As you would expect, the loop will continue to execute while the modifier is true.
>> n = 3
=> 3
>> begin
?> puts n
>> n -= 1
>> end while n > 0
3
2
1
=> nil
While I would be happy to never see this idiom again, begin...end is quite powerful. The following is a common idiom to memoize a one-liner method with no params:
def expensive
@expensive ||= 2 + 2
end
Here is an ugly, but quick way to memoize something more complex:
def expensive
@expensive ||=
begin
n = 99
buf = ""
begin
buf << "#{n} bottles of beer on the wall\n"
# ...
n -= 1
end while n > 0
buf << "no more bottles of beer"
end
end
原作者:Jeremy Voorhis这里的内容是复制的,因为它似乎是从原始站点删除的。副本也可以在Web Archive和Ruby Buzz论坛上找到。——蜥蜴比尔