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

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

    You can use methods like parent, parent_name, parents to get outer modules, eg.:

    class A
      def self.a; puts 'a!' end
    
      class B
        def self.b; parent.a end
      end
    end
    
    A::B.b #=> a!
    
    0 讨论(0)
提交回复
热议问题