在Ruby中获取用户输入
我要求用户输入我要创建的新类的名称。我的代码是:在Ruby中获取用户输入,ruby,user-input,Ruby,User Input,我要求用户输入我要创建的新类的名称。我的代码是: puts "enter the name for a new class that you want to create" nameofclass = gets.chomp nameofclass = Class.new puts "enter the name for a new method that you want to add to that class" nameofmethod = gets.chomp nameofclass.
puts "enter the name for a new class that you want to create"
nameofclass = gets.chomp
nameofclass = Class.new
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
为什么这不起作用
另外,我想让用户输入我要添加到该类中的方法的名称。我的代码是:
puts "enter the name for a new class that you want to create"
nameofclass = gets.chomp
nameofclass = Class.new
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
这也不起作用。以下代码:
nameofclass = gets.chomp
nameofclass = Class.new
由机器解释为:
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"
正如您所看到的,如果您遵循上面的步骤,那么有一个变量会被赋值两次。当第二个赋值发生时,第一个赋值将丢失
您试图做的大概是创建一个新类,并将其命名为与gets.chomp
的结果相同的名称。为此,可以使用eval:
nameofclass = gets.chomp
code = "#{nameofclass} = Class.new"
eval code
还有其他方法,这是Ruby,但是eval
可能是最容易理解的。我喜欢它对正在发生的事情的解释
要避免使用非常危险的eval
,请尝试以下操作:
Object.const_set nameofclass, Class.new
我应该注意到,我同意
eval
在生产代码中很难看。然而,首先,这似乎是一个非常实验性的案例;你永远不会想做这样的事。eval
的好处是它对于初学者来说很容易理解,并且可以作为元编程的入门。