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

后端 未结 7 2030
-上瘾入骨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:09

    I typically do something like this:

    class A
      def a
        puts "hi"
      end
    
      def createB
        B.new self
      end
    
      class B
        def initialize(parent)
          @parent=parent
        end
    
        def b
          @parent.a
        end
      end
    end
    
    A.new.createB.b
    

提交回复
热议问题