1

我正在学习 Ruby,并且在Time. 这是我需要通过的 rspec 的要求:

it "takes about 1 second to run a block that sleeps for 1 second" do
  elapsed_time = measure do
    sleep 1
  end
  elapsed_time.should be_within(0.1).of(1)
end

我的代码measure是:

def measure
  start = Time.now
  elapse = Time.now - start
end

我错过了什么?我无法通过睡眠 1 秒的街区。我试图测试并调用该块:

a = Proc.new{puts "hello"}
sleep 1
measure

# => Unknown error
4

2 回答 2

3

您错过了yield在您的 measure 方法中调用:

def measure
  start = Time.now
  yield if block_given?
  elapse = Time.now - start
end
于 2013-05-17T10:21:50.297 回答
1

要了解 Ruby 的代码块,我建议您阅读这篇博文

从这个例子可以看出:

def my_ordinary_method()
  #do stuff
  yield #the instruction that calls the block
  #do more stuff
end

def the_caller()
  #do stuff
  my_ordinary_method() do
    puts "I am the block. The one everyone talks about!"
    puts "I am gentle, colorful and polite"
  end
end

取自上面的链接。

您的代码应如下所示:

def measure
  start = Time.now
  yield if block_given?
  elapse = Time.now - start
end
于 2013-05-17T10:31:48.180 回答