gpt4 book ai didi

ruby - 将类名分配给变量

转载 作者:太空宇宙 更新时间:2023-11-03 17:22:34 24 4
gpt4 key购买 nike

我在某人的代码中看到了这样的东西:

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 类本身。 aTest01实例x Test01.

Test01.class # returns 'Class'
x.class # returns 'Class'
a.class # returns 'Test01' because it is an instance of 'Test01'

关于ruby - 将类名分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28765006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com