【问题标题】:Take String (Ex. "Car") and turn it into Class in Ruby [duplicate]取字符串(例如“汽车”)并将其转换为 Ruby 中的类 [重复]
【发布时间】:2016-03-20 11:55:32
【问题描述】:

我有一个我想调用的类的字符串表示。该类已存在。

klass = "Broseph"
Class.new(Broseph)
# => #<Class:0x007f9f0c1cc8b8>
Class.new("Broseph")
# => TypeError: superclass must be a Class (String given)

怎样才能把字符串变成一个类呢?如何在已表示为字符串的类上调用类方法?我还需要将参数传递给该类方法。

【问题讨论】:

    标签: ruby metaprogramming


    【解决方案1】:

    你可以使用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
    

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多