我正在学习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秒的块。我试着测试并调用block:
a = Proc.new{puts "hello"}
sleep 1
measure
# => Unknown error
您错过了在度量方法中调用yield
:
def measure
start = Time.now
yield if block_given?
elapse = Time.now - start
end
要理解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