获取字符串(例如 "Car")并将其转换为 Ruby 中的 Class
Take String (Ex. "Car") and turn it into Class in Ruby
我有要调用的 class 的字符串表示形式。 class 已经存在。
klass = "Broseph"
Class.new(Broseph)
# => #<Class:0x007f9f0c1cc8b8>
Class.new("Broseph")
# => TypeError: superclass must be a Class (String given)
如何把字符串变成class?如何在已表示为字符串的 class 上调用 class 方法?我还需要将参数传递给 class 方法。
您可以使用 const_get
:
klazz = Object.const_get('Broseph')
然后在 klazz
上调用方法,例如:
klazz.some_method # when you know the method is fixed
klazz.send('some_method') # when the method also is stored in a string
我有要调用的 class 的字符串表示形式。 class 已经存在。
klass = "Broseph"
Class.new(Broseph)
# => #<Class:0x007f9f0c1cc8b8>
Class.new("Broseph")
# => TypeError: superclass must be a Class (String given)
如何把字符串变成class?如何在已表示为字符串的 class 上调用 class 方法?我还需要将参数传递给 class 方法。
您可以使用 const_get
:
klazz = Object.const_get('Broseph')
然后在 klazz
上调用方法,例如:
klazz.some_method # when you know the method is fixed
klazz.send('some_method') # when the method also is stored in a string