认为 ruby​​ 中缺少方法是否可疑?

发布于 2024-12-02 12:15:15 字数 591 浏览 1 评论 0原文

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 类,并且 PersonClass 都有相同数量的方法。

现在让我们实例化 Person

a = Person.new
puts a.methods.count #=> 42 methods

如果 aPerson 的实例,那么为什么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苦行僧 2024-12-09 12:15:15
 a.methods

是实例方法,

 Person.methods

是类方法。它们不共享相同的命名空间。当您在 Person 上定义 name 时,您正在定义一个实例方法。

class Person
  def self.name
    puts "Doharey"
  end
end
=> nil
Person.methods.count
=> 113
Class.methods.count
=> 114

这里我定义了一个类方法,它也显示在方法列表中。

 a.methods

are the instance methods and

 Person.methods

are class methods. They do not share the same namespace. When you define name on Person you are defining an instance methods.

class Person
  def self.name
    puts "Doharey"
  end
end
=> nil
Person.methods.count
=> 113
Class.methods.count
=> 114

Here I've defined a class method which also shows up in the method list.

遥远的绿洲 2024-12-09 12:15:15
class Person
  def name
    puts "Doharey"
  end
end

我们的新类中有多少个实例方法?

Person.instance_methods.size
# => 72

列出一个类的所有实例方法,不包括从超类继承的任何方法:

Person.instance_methods(false)
# => [:name]

每个新类默认都是 Object 的子类:

Person.superclass
# => Object

超类中有多少个实例方法?

Object.instance_methods.size
# => 71
class Person
  def name
    puts "Doharey"
  end
end

How many instance methods are there in our new class?

Person.instance_methods.size
# => 72

List all instance methods of a class, excluding any methods inherited from the superclass:

Person.instance_methods(false)
# => [:name]

Every new class is by default a subclass of Object:

Person.superclass
# => Object

How many instance methods are there in the superclass?

Object.instance_methods.size
# => 71
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文