Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.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中的其他类_Ruby - Fatal编程技术网

对象上的私有实例方法的行为不同于Ruby中的其他类

对象上的私有实例方法的行为不同于Ruby中的其他类,ruby,Ruby,下面是我使用对象类进行的代码继承: class Object private def talk puts "hi there" end end class Child talk # outputs 'hi there' end 下面是我对一个新类的代码继承: class Parent private def talk puts "hi there" end end class Child < Parent talk #`<cla

下面是我使用对象类进行的代码继承:

class Object
  private
  def talk
    puts "hi there"
  end
end

class Child
  talk  # outputs 'hi there'
end
下面是我对一个新类的代码继承:

class Parent
  private
  def talk
    puts "hi there"
  end
end

class Child < Parent
  talk #`<class:Child>': undefined local variable or method `talk' for Child:Class (NameError)
end
类父类
私有的
def谈话
把“你好”
结束
结束
类子<父
talk#`:未定义的局部变量或子类的方法“talk”:类(NameError)
结束

为什么会有不同的行为?

在这两个示例中,您在
Child
的上下文中调用
talk
,这是
类的一个实例

在第一个示例中,实例方法
talk
Object
类上定义,而
class
是的子类

在第二个示例中,实例方法
talk
Parent
类上定义,而
class
不是的子类