我正在尝试使用 i 变量“命名”一个新类。
从另一个线程中,我得到了一些关于使用 och 'const_set' 的入门信息, 当我尝试这个时它工作正常:
name = "Person"
attributes = [:fname, :age]
klass = Object.const_set name, Struct.new(*attributes)
p = Person.new("John Doe", 42) # => #<struct Person name="John Doe", age=42>
但现在我想以不同的方式使用“名称”变量,例如更改它所保存的值等(实际上将是一个常量..?)
我正在外部检索一个名为 titleString 的字符串的新值..
但是当我尝试将其值传递给“名称”时
name = "#{titleString}"
attributes = [:fname, :age]
klass = Object.const_set name, Struct.new(*attributes)
我最终得到了一个“错误的常量名称”-错误..
怎么会这样?
最佳答案
您是否从输入(例如 gets)中获取 titleString? titleString 末尾可能有换行符。
> name="Bar\n"
=> "Bar\n"
> klass = Object.const_set name, Struct.new(*attributes)
NameError: wrong constant name Bar
关于ruby - 使用变量的 Object.const_set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9464655/