在Ruby中获取用户输入

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

这也不起作用。
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可能是最容易理解的。


3
我应该指出,我同意在生产代码中看到eval的方式不太好。然而,这似乎是一个非常实验性的案例;你永远不想做这样的事情。eval的好处在于对于初学者来说很容易理解,并且作为元编程的入门也可以正常工作。 - troelskn

5

我喜欢 troelskn的回答,因为它对所发生的事情进行了很好的解释。

为避免使用非常危险的eval,请尝试以下方法:

Object.const_set nameofclass, Class.new

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接