Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.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_Class_Methods_Instance - Fatal编程技术网

认为ruby中缺少方法是可疑的吗?

认为ruby中缺少方法是可疑的吗?,ruby,class,methods,instance,Ruby,Class,Methods,Instance,在上面的示例中,创建了一个继承自class的Person类,并且Person和class具有相同数量的方法 现在让我们实例化Person类 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 me

在上面的示例中,创建了一个继承自
class
Person
类,并且
Person
class
具有相同数量的方法

现在让我们实例化
Person

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
如果
a
Person
的一个实例,那么为什么
a
中的方法数量少于
Person
。会发生什么?有些方法是如何丢失的?他们一开始不是继承的吗?如果是,怎么做

a = Person.new
puts a.methods.count #=> 42 methods
是实例方法和

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

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

class Person
  def self.name
    puts "Doharey"
  end
end
=> nil
Person.methods.count
=> 113
Class.methods.count
=> 114
我们的新类中有多少实例方法

class Person
  def name
    puts "Doharey"
  end
end
列出类的所有实例方法,不包括从超类继承的任何方法:

Person.instance_methods.size
# => 72
默认情况下,每个新类都是Object的子类:

Person.instance_methods(false)
# => [:name]
超类中有多少实例方法

Person.superclass
# => Object

这就是我首先想到的,根据定义,对象不能有类方法。类方法只能从未实例化的类调用,而不能从类的实例调用。但“Person”类本身是“class”类的实例,实际上“Person”是一个对象。这是矛盾的。也是相关的,
Person.instance\u方法
返回实例方法列表,所以
Person.instance\u methods.count
=
Person.new.methods.count
如果是这样的话,为什么在
Person.instance\u methods
中出现的一些方法也出现在
Person.methods
中,当你说
Person.methods
时,给出了类方法和
Person.instance\u methods
给出了实例方法的列表。实例中不应存在类方法。那么像
inspect
object\u id
等方法是如何产生的呢。。。。在两个列表中都存在?因为类也是一个对象—类的实例。因此,您看到的是
Class
的实例方法。如果您只想查看自己类的类方法,请使用
Person.methods(false)
。您的
Person
类不是从
class
继承的,而是从
Object
继承的。“认为ruby中缺少方法是可疑的吗?”您是否签入了
内核#method\u missing
?[很抱歉,我就是忍不住了。]?“[对不起,就是忍不住]”=>没听懂你的话,什么?真的,只是个糟糕的笑话。但是,如果您想了解
方法\u missing
(您应该这样做!),请查看以下示例:
Object.instance_methods.size
# => 71