2010-09-12 73 views
0

我認爲這是可能在這樣的eigenclass定義attr_accessor方法:attr_accessor類問題

class IOS 
    @@modules_paths = "hello" 

    class << self 
    attr_accessor :modules_paths 
    end 

end 

puts IOS::modules_paths 

但這沒有返回。

有沒有辦法做到這一點?

回答

6

您添加到類中的attr_accessor使用類級別的實例變量,而不是類變量。在某些情況下,這實際上可能更有幫助,因爲當繼承進入圖片時,類變量可能會變得荒謬。

class IOS 
    @modules_paths = "hello" 

    class << self 
    attr_accessor :modules_paths 
    end 
end 

puts IOS::modules_paths # outputs "hello" 

如果你真的需要它使用類變量,你可以手動定義的方法,在拉的ActiveSupport和使用cattr_accessor,或者只是copy the relevant ActiveSupport methods

1

您從不會調用IOS::modules_paths= setter方法,也不會在任何地方分配相應的@modules_paths實例變量。因此,@modules_paths是單位化的,因此IOS.modules_paths返回一個單位變量。在Ruby中,未初始化的變量評估爲nilputs nil什麼都不打印。