1

在 Ruby 中,我可以写,

Dog = Class.new

所以这里,Dog是一个Object,它是 的一个实例Class

另外,我可以写

fido = Dog.new

仅当Dog是 a时才有可能Class

Dog这里是 a还是Classan Object

4

4 回答 4

5

ruby 中的所有内容都是一个Object(块除外)。这里Dog还有一个Class.

Dog = Class.new
fido = Dog.new

所以答案是:两者

于 2013-05-13T07:45:43.407 回答
5

询问对象本身,以了解它们所属的位置,如下所示:

Dog = Class.new
fido = Dog.new
Dog.instance_of? Class #=> true
fido.instance_of? Class #=> false
fido.instance_of? Dog #=> true
Dog.superclass #=> Object
Dog.is_a? Object #=> true
Dog.is_a? Class #=> true

要更详细地研究,请参阅Object model Documentation

于 2013-05-13T07:49:56.750 回答
1

我认为你犯了一些初学者反复犯的错误。您混淆了“是”的两个含义:

  • A 是 B 的一个实例,并且
  • A 是B的子类。

以你的情况,

  • Dog是(但不是子类)的实例Class,并且
  • Dog是(但不是的实例)的子类Object

所以,在不同的意义上,它是一个Class并且是一个Object

当他们说“Ruby 中的一切都是一个Object”时,并不意味着一切都是Object. 这意味着一切都是 的(自反)子类的实例Object

于 2013-05-13T10:54:22.060 回答
0

gem install y_support首先,通过在命令提示符下键入来安装“y_support” 。然后,在 irb 中:

require 'y_support/name_magic'

class Animal
  include NameMagic
end # You have created a new class
Animal.name #=> "Animal" -- the class is named Animal
class Dog < Animal
  def speak; puts "Bow wow!" end
end #=> hereby, you have created a subclass of Animal class
Cat = Class.new( Animal ) do
  def speak; puts "Meow!" end
end #=> this is another way of creating a subclass
Dog.name #=> "Dog" -- this is a class named Dog

现在

Fido = Dog.new      #=> You have created a new Dog instance
Dog.instance_names  #=> [:Fido] -- the instance is named Fido
Stripes = Cat.new   #=> You have created a new Cat instance
Cat.instance_names  #=> [:Stripes] -- the instance is named Cat
Animal.instances.size #=> 2 -- we have 2 animals thus far
Animal.instances.each do |animal| animal.speak end #=> Bow wow! Meow!

让我们创建另一只狗:

Spot = Dog.new      #=> Another Dog instance
Dog.instances.size  #=> 2 -- we now have 2 dogs
Fido.class          #=> Dog -- Fido is an instance of class Dog
Spot.class          #=> Dog -- Spot is also an instance of class Dog
Fido.class.ancestors #=> The output shows you that Fido is also an Animal
Animal.instances.size #=> 3 -- together, we have 3 animals
Animal.instance_names #=> [:Fido, :Stripes, :Spot]
Animal.instance( :Fido ).speak #=> Bow wow!
Animal.instances.each &:speak #=> Bow wow! Meow! Bow wow!

明白了吗?请记住,在 Ruby 中,永远不要没有NameMagic.

于 2013-06-30T20:52:23.327 回答