2

I tried to implement a singleton pattern in ruby, just want to know why I 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" as a private class method, and try to call the "new" in my singleton method "getInstance"

test output

>> require "./test.rb" => true >> Test.getInstance NoMethodError: private method `new' called for Test:Class from ./test.rb:7:in `getInstance' from (irb):2 >> 
4
  • You cannot access new with a receiver because it is now private. And it is you who made it private. Not clear why you are doing such contradictory thing and wondering over it. Commented Jul 15, 2013 at 9:13
  • 1
    not sure why this is down voted. @sawa, someone with java background can make this mistake easily and I think this question can be helpful to them. In JAVA, we can access any private stuff inside a class declaration, Commented Jul 15, 2013 at 9:18
  • 1
    Ruby is not Java. Don't use a method without even knowing what it does. Not reading the document is just laziness. Commented Jul 15, 2013 at 9:21
  • 2
    I know ruby is not java. I think the forum have tolerance for newbie questions, and most people is willing to help others pass their learning curves. Save your arrogance. Commented Jul 15, 2013 at 9:26

2 Answers 2

3

Since ::new is a private method, you can't access it by sending a message to the class constant. It'll work to just send it to implicit self by omitting the receiver, though.

Additionally, since this is a class method, its instance variable scope is already class-level, so you don't need to use @@ class variables. An instance variable will work just 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 
Sign up to request clarification or add additional context in comments.

Comments

2
private_class_method :new NoMethodError: private method `new' called for Test:Class 

That's why. Private methods cannot be invoked with explicit receiver. Try using send.

@@instance = Test.send(:new) 

or with implicit receiver (because self is Test)

@@instance = new 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.