爲什麼private
僅適用於實例方法,而不適用於類方法?不僅如此,爲什麼private_class_method
方法使類方法變爲私有方法?Ruby中的private和private_class_method關鍵字
class Foo
private
def self.private_class_method
puts 'hello from private_class_method'
end
def private_instace_method
puts 'hello from private_instace_method'
end
end
Foo.private_class_method #Ok!
Foo.new.private_instace_method #error: private method `private_instace_method' called for #<Foo:0x000001020873b8>
這個怎麼樣?
class Foo
private_class_method :private_class_method
def self.private_class_method
puts 'hello from private_class_method'
end
private
def private_instace_method
puts 'hello from private_instace_method'
end
end
Foo.private_class_method #Ok!
Foo.new.private_instace_method #error: private method `private_instace_method' called for #<Foo:0x000001020873b8>
如何使類方法爲私有?
[如何訪問Ruby中的私有類方法?](http://stackoverflow.com/questions/27859296/how-to-access-private-class-methods-in-ruby) – Severin 2015-02-08 07:43:42
此外,你應該考慮'private_class_method'方法名與'private_class_method'類方法相交http://ruby-doc.org/core-1.9.3/Module.html#method-i-private_class_method – freemanoid 2015-02-08 09:24:40