كيفية استدعاء الفئات بشكل حيوي دون استخدام التقييم؟

StackOverflow https://stackoverflow.com/questions/508331

  •  21-08-2019
  •  | 
  •  

سؤال

هل من الممكن التخلص من تقييم بيان أدناه؟يقوم الكود أدناه بتصفية جميع الفئات المشتقة من النوع 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 هي الطريقة الوحيدة التي أعرفها لتحويل السلسلة إلى ثابت.إنها حتى الطريقة التي تقوم بها القضبان: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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top