RUBY: how to resolve circular dependency in constant definitions?

class A
  X = 9
  Y = B::X
end

class B
  X = 8
  Y = A::X
end

I have two classes, each of which defines some constants, but requires constants from the other, as shown above, but this gives me an error:

circle.rb: 7: in <class:A>': uninitialized constant A::B (NameError) from circular.rb:5:in'

Is there any way to resolve the error?

Thank.

+3
source share
1 answer

This works if you split the definition of A into two parts:

class A
  X = 9
end

class B
  X = 8
  Y = A::X
end

class A
  Y = B::X
end
+3
source

Source: https://habr.com/ru/post/1778497/


All Articles