Why cant there be classes inside methods in Ruby?

前端 未结 4 1183
天涯浪人
天涯浪人 2021-02-19 18:29

Can I create Ruby classes within functions bodies ? I seem to be getting error which tells me its not allowed but I think it should be as classes are too objects here.



        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 19:01

    You can create classes from within methods and assign them to a constant, as in the following

    class A
      def create_class class_name
        new_class = Class.new
        new_class.send :define_method, :speak do
          "Hi, There"
        end
        Object.const_set class_name, new_class
      end
    end
    
    A.new.create_class "Harry"
    h = Harry.new
    puts h.speak  # responds => "Hi, There"
    

    because a class name as in String is just a constant in ruby unlike many other languages.

提交回复
热议问题