开发者

How to define a Class method like MyObject[:test]= 'test'

开发者 https://www.devze.com 2023-02-23 04:29 出处:网络
This is what I want do cr开发者_StackOverflow中文版eate, but it doesnt work: class MyObject def self.[]=(key, value)

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.

  1. Instance variables can be used without initialization, but class variables cannot.Programming Ruby:Class Variables and Class Methods:Class Variables:1st paragraph

  2. Even if a class variable was able to be used without initialization, it would be implicitly initialized to nil, and you cannot suddenly use the Hash#[] method.

0

精彩评论

暂无评论...
验证码 换一张
取 消