Why cant there be classes inside methods in Ruby?

前端 未结 4 1179
天涯浪人
天涯浪人 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 18:37

    you can create classes, but you cannot assign constants from inside a method.

    this example works:

    class A
      def a
        b = Class.new
        def b.xxx
          "XXX"
        end
        b
      end
    end
    
    a = A.new.a
    p a         # #
    p a.xxx     # "XXX"
    

提交回复
热议问题