I made a class which has simply class methods, the intention is that the
class will not be instaniated. Inside it, one method was made private
(using private_class_method) however when I try to call that private
method from another class method I get a NoMethodError exception.
I would have expected it to work as I am not attempting to call the
method from outside the class. Anyone any thoughts?
Output is:
ruby class_method_test.rb
class_method_test.rb:5:in store': private method clear’ called for
Test:Class (NoMethodError)
from class_method_test.rb:21
Exit code: 1
Code:
class Test
@@value = nil
def Test.store (x)
Test.clear #line 5
value = x
end
def Test.get_value
x
end
def Test.clear
value = nil
end
private_class_method :clear
end #test
Test.store(1) #line 21
p Test.get_value
Test.clear
As I understand it, private methods can only be used by an object of
the same class. The store method is public, and is available to any
sub-class of Test, whether or not that sub-class inherits the private
clear method. Therefore, to properly enforce the private constraint,
Ruby probably should not let you do what you are trying to do.
But someone else should confirm this.
···
On Wednesday, December 4, 2002, at 06:02 AM, Robert McGovern wrote:
I made a class which has simply class methods, the intention is that
the class will not be instaniated. Inside it, one method was made
private (using private_class_method) however when I try to call that
private method from another class method I get a NoMethodError
exception.
I would have expected it to work as I am not attempting to call the
method from outside the class. Anyone any thoughts?
Output is:
ruby class_method_test.rb
class_method_test.rb:5:in store': private method clear’ called for
Test:Class (NoMethodError)
from class_method_test.rb:21
Exit code: 1
Code:
class Test
@@value = nil
def Test.store (x)
Test.clear #line 5
value = x
end
def Test.get_value
x
end
def Test.clear
value = nil
end
private_class_method :clear
end #test
Test.store(1) #line 21
p Test.get_value
Test.clear
First apologies that the rest of the test class didn’t work properly, I
forgot all my @@'s.
# strange :-))
def Test.store (x)
Test.clear #line 5
clear # a private method must be called without receiver
value = x
# strange :-))
Thanks Guy, I must admit I wasn’t expecting that to work and hence
didn’t try it.
I suppose it kinda makes sense in terms of when you use
private_class_method you have to use the method name without the
receiver, but as you say strange!
(I did spend a little time confused as to why using private before a
method worked but private :method_name or private :Receiver.method_name
didn’t, until I realised there was a private_class_method)