How can a nested class access a method in the outer class in Ruby?

后端 未结 7 2041
-上瘾入骨i
-上瘾入骨i 2021-02-12 13:58
def class A
  def a
    raise \"hi\" #can\'t be reached
  end

  class B
    def b
      a() #doesn\'t find method a.
    end
  end
end

I want to invok

7条回答
  •  时光说笑
    2021-02-12 14:28

    If you want then nested class to extend the outer class, then do so:

    class Outer
    
      class Inner < Outer
        def use_outer_method
          outer_method("hi mom!")
        end
      end
    
      def outer_method(foo)
        puts foo
      end
    
    end
    
    foo = Outer::Inner.new
    foo.use_outer_method        #<= "hi mom"
    foo.outer_method("hi dad!") #<= "hi dad"
    

提交回复
热议问题