2011-10-12 24 views
0

在Ruby中,我怎麼能檢測未使用/未分配的表情和做一些與他們這樣的:紅寶石:檢測未使用/未分配的表情

class Thing 
    attr_accessor :name 
    def initialize(name) 
    @name = name 

    #if a new instantiation of this class is not assigned to anything 
    #or used by a calling method, then make a variable called #{name} 
    #and assign it to this new instantiation 
    if not assigned_or_used 
     global_variable_set(name, this) 
    end 
    end 

    def to_s 
    "Hi from #{name}" 
    end 
end 

現在我想實例化一個東西,沒有它明確地分配給一個變量,而是在實例化時自動分配一個變量:

bob = Thing.new("bob") 
puts bob 
#=> "Hi from bob" 
#works ordinarily 

Thing.new("fred") 
puts fred 
#=> "Hi from fred" 
#works after implementing the code for instantiation of Thing 
#without explicit assignment/use by a method 
+1

是你的單身之後? –

+0

絕對不是。 – themirror

回答

2

Yeesh,我不知道。我可能會誤解,但這聽起來像一個真的很不好主意(也許你可以提供一個具體的例子爲什麼你想這樣做)。

問題浮現在腦海中:

  • 你只是想挽回按鍵嗎?
  • 如果名稱衝突(您連續撥打Thing.new("fred")兩次)會發生什麼?變量會發生什麼變化?
  • 你真的想這樣做嗎,你真的想在它上面創建一個全局變量嗎?剝離掉所有範圍的安全性?
  • 如果這甚至是可能的,你可以挖掘垃圾收集器來做到這一點?

垃圾收集器自動(但只是週期性地)在沒有對象存在引用時釋放內存。似乎如果你這樣做(爲所有「事物」未分配創建變量),你會創建一個內存泄漏,並繞過垃圾收集器的生活目的。你也可能在與垃圾收集器對抗 - 也就是說,在你創建一個對象之後,如果垃圾收集器在那之間運行,並且當創建變量時,你仍然會丟失對象。

+0

我想搞亂垃圾收集器的工作方式不是實現OP目標的方法。 – themirror

+0

我認爲這實際上是一個非常有趣的問題。出於好奇,你最初的目標是什麼? – jefflunt