Why cant there be classes inside methods in Ruby?

前端 未结 4 1205
天涯浪人
天涯浪人 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:56

    class A
      def method
        self.class.const_set :B, Class.new {
          def foo
            'bar'
          end
        }
      end
    end
    
    A.new.method
    A::B.new.foo # => 'bar'
    

    However, why do you want to assign a constant inside a method? That doesn't make sense: constants are constant, you can only assign to them once which means you can only run your method once. Then, why do you write a method at all, if it is only ever going to be run once, anyway?

提交回复
热议问题