何时以及为何在Ruby中使用Loop Do Construct

时间:2013-05-29 11:55:12

标签: ruby loops language-construct

我最近遇到过使用Loop Do的问题/解决方案。到目前为止,我在学习Ruby编程时很少见到这一点(我是一名没有CS经验的初学者)。

# Write a function, `nearest_larger(arr, i)` which takes an array and an
# index.  The function should return another index, `j`: this should
# satisfy:
#
# (a) `arr[i] < arr[j]`, AND
# (b) there is no `j2` closer to `i` than `j` where `arr[i] < arr[j]`.
#
# In case of ties (see example beow), choose the earliest (left-most)
# of the two indices. If no number in `arr` is largr than `arr[i]`,
# return `nil`.
#
# Difficulty: 2/5

describe "#nearest_larger" do
  it "handles a simple case to the right" do
    nearest_larger([2,3,4,8], 2).should == 3
  end

  it "handles a simple case to the left" do
    nearest_larger([2,8,4,3], 2).should == 1
  end

  it "treats any two larger numbers like a tie" do
    nearest_larger([2,6,4,8], 2).should == 1
  end

  it "should choose the left case in a tie" do
    nearest_larger([2,6,4,6], 2).should == 1
  end

  it "handles a case with an answer > 1 distance to the left" do
    nearest_larger([8,2,4,3], 2).should == 0
  end

  it "handles a case with an answer > 1 distance to the right" do
    nearest_larger([2,4,3,8], 1).should == 3
  end

  it "should return nil if no larger number is found" do
    nearest_larger( [2, 6, 4, 8], 3).should == nil
  end
end

def nearest_larger(arr, idx)
  diff = 1
  loop do
    left = idx - diff
    right = idx + diff

    if (left >= 0) && (arr[left] > arr[idx])
      return left
    elsif (right < arr.length) && (arr[right] > arr[idx])
      return right
    elsif (left < 0) && (right >= arr.length)
      return nil
    end

    diff += 1
  end
end
 nearest_larger([2,4,3,8], 1)

有人可以向我解释何时是使用“循环做”构造的最佳时间,而不是通常的“while”或“除非”或“每个”构造?

5 个答案:

答案 0 :(得分:24)

添加到之前的答案,

“loop do”构造在使用外部迭代器时也提供了更清晰的语法,例如

没有“循环做”

my_iterator = (1..9).each
begin
  while(true)
    puts my_iterator.next
  end
rescue StopIteration => e
  puts e
end

现在用“循环做”这将成为

my_iterator = (1..9).each
loop do
  puts my_iterator.next
end

并且处理了异常。它还允许您同时循环遍历两个集合,并且只要其中一个集合耗尽,循环就会优雅地退出,

iterator = (1..9).each
iterator_two = (1..5).each

loop do
  puts iterator.next
  puts iterator_two.next
end

将打印:1,1,2,2,3,3,4,4,5,5,6。

有关详情,请访问:ruby-docs.org

答案 1 :(得分:12)

在没有loop的语言中,您可以使用while构造,如:

while( true ) {
  # Do stuff until you detect it is done
  if (done) break;
}

关键是你在不知道要执行多少次迭代的情况下启动循环(或者事先很难计算),但是很容易检测循环何时结束。此外,对于特定情况,您可能会发现等效的while (! done) { # do stuff }语法笨拙,因为完成条件可能发生在循环的中途,或者在多个位置。

Ruby的loopwhile( true )基本相同 - 实际上你可以使用while( true )几乎可以互换。

在给定的示例中,每次迭代中都有以下返回点:

if (left >= 0) && (arr[left] > arr[idx])
  return left   # <-- HERE
elsif (right < arr.length) && (arr[right] > arr[idx])
  return right  # <-- HERE
elsif (left < 0) && (right >= arr.length)
  return nil    # <-- HERE
end 

如果没有达到最终条件,这里还有一个暗示的“其他继续循环”。

这些多个可能的退出点可能是作者选择loop构造的原因,尽管在实践中使用Ruby有很多方法可以解决这个问题。给定的解决方案代码不一定优于所有其他可能性。

答案 2 :(得分:2)

使用loop do构造允许您打破条件。

例如:

i=0
loop do
  i+=1
  print "#{i} "
  break if i==10
end 

当您知道将要处理的元素数量时,您可能希望使用此方法,类似于for each循环

的元素数量

答案 3 :(得分:2)

带有'loop'构造的

循环将无限地执行给定的块  直到块内的代码在某些条件下中断。

当你没有一个集合来循环时,可以使用它  'each'和'for'无法工作的地方。

'loop'和while / until之间的差异是while / until将  当某个条件满足时执行给定的块,如下所示  循环的情况没有条件启动,条件位于内部  循环的块。

为了更好地理解阅读文档。

http://www.ruby-doc.org/core-1.9.2/Kernel.html#method-i-loop

答案 4 :(得分:0)

假设您要放置许多条件,将它们放在内联中可能会更整洁,例如,相反:

x = 0
while x <= 10
    num = gets

    break if num < 1
    break if /\D/.match? num.to_s

    puts num.to_f ** 2
end

插入中断使其更具可读性

x = 0
loop do
    num = gets

    break if num < 1
    break if x <= 10
    break if /\D/.match? num.to_s

    puts num.to_f ** 2
end