5

我要求用户输入我要创建的新类的名称。我的代码是:

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

这也不起作用。

4

2 回答 2

11

以下代码:

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可能是最容易理解的。

于 2009-07-27T08:00:14.600 回答
5

我喜欢troelskn 的回答,因为它解释了正在发生的事情。

为了避免使用非常危险的eval,试试这个:

Object.const_set nameofclass, Class.new
于 2009-07-27T13:09:34.157 回答