我正在学习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
答案 0 :(得分:3)
您错过了在测量方法中调用yield
:
def measure
start = Time.now
yield if block_given?
elapse = Time.now - start
end
答案 1 :(得分:1)
要了解Ruby的代码块,我建议你阅读this blog post。
正如您在此示例中所看到的那样:
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