This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: Private constants?
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
In the course of creating pure Ruby versions of former C extensions I've had to copy/paste a bunch of constants out of the Windows header files and into the Ruby files. The problem is that many of these are meaningless to users, and I don't really want them to be visible. Unfortunately, there's no way to make constants private.
Or is there?
Purely by accident I noticed something interesting. Consider this code:
class Foo
BAR = 1
p BAR # 1
end
p File.constants # ["BAR"]
p File::BAR # 1
Ok, that's what we expected. Now try this:
class Foo
_BAR = 1
p _BAR # 1
end
p File.constants # []
p File::_BAR # NoMethodError: undefined method `_BAR' for Foo:Class
Like, whoa. Leading underscores appear to make your constant invisible to the outside world (short of an eval, anyway).
Either I'm really tired (which I am) and I've completely forgotten something I should know, or this is undocumented (though cool) behavior.