Ruby with Rspec - 这个测试如何通过?

时间:2014-01-09 19:13:10

标签: ruby rspec

此测试通过验证,但如何?

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

#Function
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

我正在研究一些ruby示例,我无法理解此测试如何通过验证。从0返回的位置是什么?

1 个答案:

答案 0 :(得分:0)

idx为2且diff为2时(即第二次循环播放),left2 - 2 = 0arr[0] == 8arr[2] == 4大于left。然后该函数返回{{1}},该值为零。