2013-05-17 57 views
1

我在学Ruby,遇到困难时刻Time。下面是从我需要通过rspec的要求:Ruby时间运行模块,睡眠时间为x秒

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 
+1

参数添加到您的方法和内部产生的。 – oldergod

回答

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 
3

你错过了叫yield您的测量方法中:

def measure 
    start = Time.now 
    yield if block_given? 
    elapse = Time.now - start 
end