Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby中的private和private_class_方法关键字_Ruby - Fatal编程技术网

Ruby中的private和private_class_方法关键字

Ruby中的private和private_class_方法关键字,ruby,Ruby,为什么private仅适用于实例方法而不适用于类方法?不仅如此,为什么private\u class\u methodmethod不将类方法私有化 class Foo private def self.private_class_method puts 'hello from private_class_method' end def private_instace_method puts 'hello from private_instace_metho

为什么
private
仅适用于实例方法而不适用于类方法?不仅如此,为什么
private\u class\u method
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
私有的
def self.private_class_方法
放置“hello from private_class_method”
结束
def专用安装方法
将“hello from private\u instance\u method”
结束
结束
Foo.private_class#u method#好的!
Foo.new.private_instance_method#错误:调用了private方法'private_instance_method'#
这个怎么样

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>
class-Foo
私有类方法:私有类方法
def self.private_class_方法
放置“hello from private_class_method”
结束
私有的
def专用安装方法
将“hello from private\u instance\u method”
结束
结束
Foo.private_class#u method#好的!
Foo.new.private_instance_method#错误:调用了private方法'private_instance_method'#

如何使类方法私有化?

您可以创建如下私有类方法:

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 
或者像这样:

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 
class-Foo

类可能的副本,也应该考虑<代码> PrimaTyCaseLoad方法< /Cord>方法名称与 PrimaTyCyrasyMead < /Cord>类方法相交,为什么第一种情况产生错误<代码> PrimeTyActhyType方法:错误的参数数(1为0)(AgulSturor)< /C> >?@ AlexanderSupertramp两种版本都适用于我。您使用的是哪个版本的Ruby?我的意思是,错误不应该被称为
私有方法吗?它是2.1.2p95
错误的参数数量
是另一个错误,如果您尝试使用参数调用该方法(示例不接受参数),则会引发该错误。啊,这是因为它的标题为
private\u class\u method
——与Ruby的方法相同。