Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
评估Ruby while循环底部的退出条件_Ruby - Fatal编程技术网

评估Ruby while循环底部的退出条件

评估Ruby while循环底部的退出条件,ruby,Ruby,我有一个关于Ruby循环的非常基本的问题 此程序以书面形式返回第i个素数+1,即示例应返回17。我知道我可以简单地返回cand-1,但我想知道Ruby是如何检查答案是否在while循环的底部找到的,如果没有找到,则只递增 def ith_prime(i) pI = 0 # primes index divs = [] cand = 2 until pI == i do if divs.find { |div| cand%div == 0 } == nil

我有一个关于Ruby循环的非常基本的问题

此程序以书面形式返回第i个素数+1,即示例应返回17。我知道我可以简单地返回cand-1,但我想知道Ruby是如何检查答案是否在while循环的底部找到的,如果没有找到,则只递增

def ith_prime(i)
  pI = 0 # primes index
  divs = []
  cand = 2

  until pI == i do 
    if divs.find { |div| cand%div == 0 } == nil
        divs << cand
        pI += 1
    end
    cand += 1
  end
  cand
end

puts ith_prime(7)
> 18
我使用循环,而不是在大部分时间内或直到。这样我就可以把退出条件放在循环中的任何地方

如果我正确理解了这个问题,我会这样写:

def ith_prime(i)
  pI = 0 # primes index
  divs = []
  cand = 2

  loop do
    unless divs.find { |div| cand%div == 0 }
      divs << cand
      pI += 1
    end

    break if pI == i

    cand += 1
  end

  cand
end
我使用循环,而不是在大部分时间内或直到。这样我就可以把退出条件放在循环中的任何地方

如果我正确理解了这个问题,我会这样写:

def ith_prime(i)
  pI = 0 # primes index
  divs = []
  cand = 2

  loop do
    unless divs.find { |div| cand%div == 0 }
      divs << cand
      pI += 1
    end

    break if pI == i

    cand += 1
  end

  cand
end

正是我想要的。谢谢正是我想要的。谢谢