对象上的私有实例方法的行为不同于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
不是的子类