How to define a Class method like MyObject[:test]= 'test'
This is what I want do cr开发者_StackOverflow中文版eate, but it doesnt work:
class MyObject
def self.[]=(key, value)
@@internal_hash[key] = value
end
end
I don't understand why overriding the self dot bracket doesnt work.
You need to initialize the class variable.
class MyObject
@@internal_hash = {}
def self.[]=(key, value)
@@internal_hash[key] = value
end
end
This is for two reasons.
Instance variables can be used without initialization, but class variables cannot.Programming Ruby:Class Variables and Class Methods:Class Variables:1st paragraph
Even if a class variable was able to be used without initialization, it would be implicitly initialized to
nil
, and you cannot suddenly use theHash#[]
method.
精彩评论