认为 ruby 中缺少方法是否可疑?
class Person
def name
puts "Doharey"
end
end
puts Person.class #=> this out puts Class
puts Class.methods.count #=> 82 methods
puts Person.methods.count #=> 82 methods
在上面的示例中,创建了一个从 Class
继承的 Person
类,并且 Person
和 Class
都有相同数量的方法。
现在让我们实例化 Person
类
a = Person.new
puts a.methods.count #=> 42 methods
如果 a
是 Person
的实例,那么为什么 a
中的方法数量较少比人
。会发生什么 ?有些方法怎么会丢失?难道它们一开始就不是遗传的吗?如果是这样怎么办?
class Person
def name
puts "Doharey"
end
end
puts Person.class #=> this out puts Class
puts Class.methods.count #=> 82 methods
puts Person.methods.count #=> 82 methods
In the above example a Person
class is created which inherits from Class
and both Person
and Class
has equal number of methods.
Now lets instantiate Person
class
a = Person.new
puts a.methods.count #=> 42 methods
If a
is an instance of Person
then why are the number of methods less in a
than Person
. What happens ? how some methods go missing ? Are they not inherited in the first place ? If so how ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是实例方法,
是类方法。它们不共享相同的命名空间。当您在
Person
上定义name
时,您正在定义一个实例方法。这里我定义了一个类方法,它也显示在方法列表中。
are the instance methods and
are class methods. They do not share the same namespace. When you define
name
onPerson
you are defining an instance methods.Here I've defined a class method which also shows up in the method list.
我们的新类中有多少个实例方法?
列出一个类的所有实例方法,不包括从超类继承的任何方法:
每个新类默认都是 Object 的子类:
超类中有多少个实例方法?
How many instance methods are there in our new class?
List all instance methods of a class, excluding any methods inherited from the superclass:
Every new class is by default a subclass of Object:
How many instance methods are there in the superclass?