evalを使用せずにクラスを動的に呼び出すにはどうすればよいですか?
質問
取り除くことは可能ですか? 評価 以下の発言?以下のコードは、BaseClass 型から派生したすべてのクラスをフィルターで除外します。その後、これらのクラスがインスタンス化され、メソッド「hello」が呼び出されます。
module MySpace
class BaseClass
def hello; print "\nhello world"; end
end
class A<BaseClass
def hello; super; print ", class A was here"; end
end
class B<BaseClass
def hello; super; print ", I'm just a noisy class"; end
end
MySpace.constants.each do | e |
c=eval(e)
if c < BaseClass
c.new.hello
end
end
end
したがって、実行後の出力は次のようになります。
こんにちは、私はただの騒々しいクラスです
こんにちは、世界、クラスAがここにありました
不必要な使用だと思います 評価 悪です。そして、を使用するかどうかはわかりません 評価 ここでは必須です。「BaseClass」型からすべてのクラスを動的に呼び出す、より賢い方法はありますか?
解決
c = MySpace.const_get(e)
他のヒント
eval は、私が知っている文字列を定数に変換する唯一の方法です。それは Rails でも行われる方法です。http://api.rubyonrails.com/classes/Inflector.html#M001638
奇妙なのは、定数が文字列を返すことです。
見ましたか class_eval
その代わり?
------------------------------------------------------ Module#class_eval mod.class_eval(string [, filename [, lineno]]) => obj mod.module_eval {|| block } => obj ------------------------------------------------------------------------ Evaluates the string or block in the context of _mod_. This can be used to add methods to a class. +module_eval+ returns the result of evaluating its argument. The optional _filename_ and _lineno_ parameters set the text for error messages. class Thing end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123) produces: Hello there! dummy:123:in `module_eval': undefined local variable or method `code' for Thing:Class
所属していません StackOverflow