Why cant there be classes inside methods in Ruby?

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

    The question is about creating classes, but in the comment you talk about creating anonymous objects. Not the same thing.

    If you need anonymous object, you can always do Object.new. If you need simple struct-like container, you should take a look at Struct class. With it, you can do something like:

    def foo
      anon_obj = Struct.new(:prop1, :prop2).new
      anon_obj.prop1 = 123
      anon_obj.prop2 = 'bar'
    
      return anon_obj
    end
    

    BTW, Ruby is a strongly typed language. But it is a dynamic typed as well, and you can't expect it to behave like static-typed.

提交回复
热议问题