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"

ご覧のとおり、上記に従うと、1つの変数があり、2回割り当てられます。2番目の割り当てが発生すると、最初の割り当ては失われます。

あなたがやろうとしていることは、おそらく新しいクラスを作成し、の結果と同じ名前を付けることです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 に答える