我要求用户输入我要创建的新类的名称.我的代码是:
puts "enter the name for a new class that you want to create"
nameofclass = gets.chomp
nameofclass = Class.new
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?
此外,我想要求用户输入我要添加到该类的方法的名称.我的代码是:
puts "enter the name for a new method that you want to add to that class"
nameofmethod = gets.chomp
nameofclass.class_eval do
def nameofmethod
p "whatever"
end
end
Run Code Online (Sandbox Code Playgroud)
这也不起作用.
tro*_*skn 11
以下代码:
nameofclass = gets.chomp
nameofclass = Class.new
Run Code Online (Sandbox Code Playgroud)
由机器解释为:
Call the function "gets.chomp"
Assign the output of this call to a new variable, named "nameofclass"
Call the function "Class.new"
Assign the output of this call to the variable "nameofclass"
Run Code Online (Sandbox Code Playgroud)
如您所见,如果您按照上述步骤操作,则会有一个变量,该变量将被分配两次.当第二个赋值发生时,第一个赋值丢失.
你想要做的,可能是创建一个新类,并将其命名为与结果相同gets.chomp.为此,您可以使用eval:
nameofclass = gets.chomp
code = "#{nameofclass} = Class.new"
eval code
Run Code Online (Sandbox Code Playgroud)
还有其他方法,这是Ruby,但eval可能是最容易理解的.
我喜欢troelskn的答案,因为它解释了发生了什么.
为避免使用非常危险eval,请尝试以下方法:
Object.const_set nameofclass, Class.new
Run Code Online (Sandbox Code Playgroud)