i tried implement singleton pattern in ruby, want know why can not access private class method in ruby
class test private_class_method :new @@instance = nil def self.getinstance if(!@@instance) @@instance = test.new end return @@instance end end
i declare "new" private class method, , try call "new" in singleton method "getinstance"
test output
>> require "./test.rb" => true >> test.getinstance nomethoderror: private method `new' called test:class ./test.rb:7:in `getinstance' (irb):2 >>
since ::new
private method, can't access sending message class constant. it'll work send implicit self
omitting receiver, though.
additionally, since class method, instance variable scope class-level, don't need use @@
class variables. instance variable work fine here.
class test private_class_method :new def self.instance @instance ||= new end end puts test.instance.object_id puts test.instance.object_id # => 33554280 # => 33554280
Comments
Post a Comment