2015-02-08 75 views
0

为什么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> 

如何使类方法为私有?

+0

[如何访问Ruby中的私有类方法?](http://stackoverflow.com/questions/27859296/how-to-access-private-class-methods-in-ruby) – Severin 2015-02-08 07:43:42

+0

此外,你应该考虑'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

回答

2

您可以创建一个私有类方法是这样的:

class Foo 
    def self.will_be_private 
    # ... 
    end 
    private_class_method :will_be_private 
end 

或者这样:

class Foo 
    class << self 
    private 
    def will_be_private 
     # ... 
    end 
    end 
end 

虽然有可能在做一个类的方法私,我很难想到一个很好的有理由这样做。海事组织一个私人类的方法是一种代码气味,并指出有一件事应该被提取到它自己的类中。

+0

为什么第一种情况会产生错误' private_class_method':错误的参数数量(1代表0)(ArgumentError)'? – 2015-02-08 07:46:15

+0

@AlexanderSupertramp两个版本都适合我。你使用哪个版本的Ruby? – spickermann 2015-02-08 08:22:19

+0

我的意思是,不应该错误已被'私人方法调用'?它是2.1.2p95 – 2015-02-08 08:26:01