我有以下代碼:
示例代碼.rb
class Foo
def bar
Timeout.timeout(0.5){
puts "Interupt this if it takes longer then 0.5 seconds"
}
end
end
foo = Foo.new()
foo.bar
當您將其粘貼到 irb 中時,上面的示例有效,但是當您將其放置在腳本中并像這樣運行時:
ruby ./sample_code.rb
它會給出以下錯誤。
Traceback (most recent call last):
1: from ./irb_works_ruby_dont.rb:11:in `<main>'
./irb_works_ruby_dont.rb:4:in `bar': uninitialized constant Foo::Timeout (NameError)
這是超時問題嗎?是否irb加載了一些普通ruby命令不加載的模塊?作為腳本運行時如何使代碼作業?
uj5u.com熱心網友回復:
最可能的解釋是 IRB 在啟動 REPL 時需要超時 - 但在此之前您的腳本檔案正在執行。您可以通過簡單地要求它來修復它:
require 'timeout'
class Foo
def bar
Timeout.timeout(0.5){
puts "Interupt this if it takes longer then 0.5 seconds"
}
end
end
foo = Foo.new
foo.bar
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358267.html
上一篇:Ruby:將十六進制字串轉換為十六進制非字串(已編輯)
下一篇:在不同物件之間傳遞程序
