attr_accessor for class question
I thought it was possible to define attr_accessor methods in a eigenclass like this:
class IOS
@@module开发者_Go百科s_paths = "hello"
class << self
attr_accessor :modules_paths
end
end
puts IOS::modules_paths
But this returns nothing.
Is there a way to do it?
The attr_accessor
you add to the class uses class-level instance variables, not class variables. This can actually be more helpful in some cases, since class variables can get ridiculous when inheritance enters the picture.
class IOS
@modules_paths = "hello"
class << self
attr_accessor :modules_paths
end
end
puts IOS::modules_paths # outputs "hello"
If you really need it to use class variables, you can define the methods manually, pull in ActiveSupport and use cattr_accessor
, or just copy the relevant ActiveSupport methods.
You never call the IOS::modules_paths=
setter method, nor do you assign to the corresponding @modules_paths
instance variable anywhere. Therefore, @modules_paths
is unitialized and thus IOS.modules_paths
returns an unitialized variable. In Ruby, uninitialized variables evaluate to nil
and puts nil
prints nothing.
精彩评论