我在某人的代码中看到了这样的东西:
class Test01
def initialize
puts "some text"
end
end
x = Test01 #this part confuses me
y = Test02 #I added this to see what will happen
a = x.new #works like expected
p a.class #Test01
p x.class #Class
p y.class #Error: uninitialized constant
- x 是什么?一次是 Class Class,另一次是 constant
- 这是不好的做法吗?如果是,正确的做法是什么?
Ruby 将所有事物都视为对象。这包括类定义以及数字、您的自定义类等。这种一致性有助于您更快地了解 Ruby。然而,它确实使一些在其他语言中不可能的事情成为可能。
当你看到
x = Test01
您基本上是在使 x
保持 Test01
的常量值。您可以将它传递给方法、进行反射,甚至可以向 x
添加新方法,就像您对 Test01
所做的那样。这就是为什么
a = x.new
b = Test01.new
本质上是相同的命令。在这两种情况下,您都将 Test01
类的实例作为新对象。 x
仍然分配给 Test01
类本身。 a
是 Test01
的实例,x
是 Test01
.
Test01.class # returns 'Class'
x.class # returns 'Class'
a.class # returns 'Test01' because it is an instance of 'Test01'
我是一名优秀的程序员,十分优秀!