평가를 사용하지 않고 동적으로 클래스를 호출하는 방법은 무엇입니까?
문제
그것을 제거 할 수 있습니까? 평가 아래 진술? 아래 코드는 유형베이스 클래스에서 파생 된 모든 클래스를 필터링합니다. 그 후 그 클래스는 인스턴스화되고 방법 '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)
다른 팁
평가는 문자열을 상수로 바꾸는 유일한 방법입니다. 철도가하는 방식도 다음과 같습니다.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