2

为什么c.f()下面不起作用b.f()?我想使用class A::C- 方式来声明一个嵌套类以避免太多的缩进。

class A
  CONSTANT = 1
end

class A
  class B
    p self # => A::B
      def f
        print CONSTANT, "\n"
      end
  end
end

class A::C
  p self # => A::C
  def f
    print CONSTANT, "\n"
  end
end

b = A::B.new
b.f() # => 1
c = A::C.new
c.f() # => `f': uninitialized constant A::C::CONSTANT (NameError)
4

2 回答 2

0

您可以使用分号将其放在一行中:

class A; class C
  ...
end end
于 2013-05-20T11:58:08.543 回答
0

您可以通过在常量前面加上前缀来解决此问题A::

class A
  CONSTANT = 1
end

class A
  class B
    def f
      puts A::CONSTANT
    end
  end
end

class A::C
  def f
    puts A::CONSTANT
  end
end

b = A::B.new
b.f() #=> 1
c = A::C.new
c.f() #=> 1
于 2013-05-20T12:05:16.293 回答