2012-01-23 109 views
1

這是一個非常簡單的問題。簡單的紅寶石對象順序

def func1 
    t2=Thread 
    while true 
     # if t2.alive?     
     # puts "GUI is running" 
     # end 
     puts Thread.t2.stop? 
     puts "func1 at: #{Time.now}" 
     sleep(1) 
    end 
end 

t1=Thread.new{func1()} 
t2=Thread.new{TheGUI()} 
t1.join 
t2.join 

t2僅在代碼中稍後聲明,因此在嘗試運行時出現錯誤。 錯誤是'未定義的局部變量或方法't2''

如何解決這個問題,而不需要重新排序我的代碼?

感謝

回答

2

您的片段是非常小的,所以這是很難說,如果你的代碼是在頂層或一類。

如果t2應該是一個全局變量,請注意Ruby prefixes global variables with a $$t2

如果t2應該是班級成員,請注意Ruby prefixes member variables with a @@t2

更新

你更新的代碼正在爲名爲t2Thread類的別名。檢查此輸出:

$ irb 
irb(main):001:0> t2=Thread 
=> Thread 
irb(main):002:0> t2 
=> Thread 
irb(main):003:0> t2.methods() 
=> ["private_class_method", "inspect", "name", "stop", "tap", "clone", "public_methods", "__send__", 
... 
irb(main):004:0> Thread.methods() 
=> ["private_class_method", "inspect", "name", "stop", "tap", "clone", "public_methods", "__send__", 

此外,該t2別名僅在力在func1函數定義的範圍。

修改你的代碼最簡單的方法是可能改變func1取一個參數:

def func1(second_thread) 
    while second_thread.alive? 
    puts "GUI is running" 
    sleep 1 
    end 
end 

t2 = Thread.new {TheGUI()} 
# pass the parameter to the function here 
t1 = Thread.new(t2) { |thread| func1(thread) } 
t1.join() 
t2.join() 
+0

我更新的代碼。謝謝 –

+0

哇,非常感謝! –