What’s the difference between these Ruby namespace conventions?

The difference lies in nesting.

In the example below, you can see that the former method using class Foo, can get the outer scope’s constant variables BAR_A without errors.

Meanwhile, class Baz will bomb with an error of uninitialized constant A::B::Baz::BAR_A. As it doesn’t bring in A::* implicitly, only A::B::*explicitly.

module A
  BAR_A = 'Bar A!'
  module B
    BAR_B = 'Bar B!'
      class Foo
        p BAR_A
        p BAR_B
      end
  end
end

class A::B::Baz
  p BAR_A
  p BAR_B
end

Both behaviors have their place. There’s no real consensus in the community in my opinion as to which is the One True Ruby Way ™. I personally use the former, most of the time.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)