2009-07-27 11 views
5

私は、作成したい新しいクラスの名前を入力するように求めます。私のコードは:ユーザー入力を取得するRuby

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 

これは機能しません。

答えて

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" 

あなたは上記に従うならば、二回に割り当てられます一つの変数があります。 2番目の割り当てが行われると、最初の割り当てが失われます。

あなたがしようとしているのは、おそらく新しいクラスを作成し、gets.chompの結果と同じ名前にすることでしょう。これを行うには、evalを使用できます。他にも方法は、あまりにもこのことRubyのですが、evalはおそらく理解するのが最も簡単です

nameofclass = gets.chomp 
code = "#{nameofclass} = Class.new" 
eval code 

+0

おかげで、あなたはたくさん –

+2

1明確な説明のために私を助けて/ -1 'eval'を推奨します。 – rampion

+2

プロダクションコードでは 'eval'が厄介であることに同意します。しかし、これは最初の非常に実験的なケースのようです。このようなことをすることは決してありません。 'eval'のメリットは、初心者にとっては理解しやすいことです。メタプログラミングの導入としてはうまくいきます。 – troelskn

5

私はtroelskn's answerが好きです。何が起こっているのかについての説明はかなりです。

非常に危険な evalを使用しないようにするには、これを試してみてください。

Object.const_set nameofclass, Class.new 
関連する問題