gpt4 book ai didi

ruby - 在 Ruby 中获取用户输入

转载 作者:数据小太阳 更新时间:2023-10-29 07:09:59 24 4
gpt4 key购买 nike

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

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

关于ruby - 在 Ruby 中获取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1186948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com