C++ namespaces in Ruby

M

Martin Elzen

Recently someone pointed out that in his opinion there was just one thing
Ruby was missing, which was something like C++ namespaces. Someone else
replied that in that case the OP should use Ruby modules. That's not
exactly true, IMO. In C++ the most significant difference between
namespaces and classes is that namespaces are open, and classes are shut.
Meaning that you can always add things to an already defined namespace, but
you can not add anything to an existing class (unless you happen to have the
source code of that class). In contrast, Ruby classes are always open, you
can always add things to them, etc. , so in that way Ruby classes are like
C++ namespaces. IMO if you want to achieve C++-like namespaces in Ruby,
you'd be best off by using a Ruby class. A Ruby class also comes closer to
a C++ namespace than a Ruby module because a Ruby class can contain
instances of objects, and as far as I know this isn't possible in a Ruby
module.

Sincerely,
Martin
 
R

Robert Klemme

Martin Elzen said:
Recently someone pointed out that in his opinion there was just one thing
Ruby was missing, which was something like C++ namespaces. Someone else
replied that in that case the OP should use Ruby modules. That's not
exactly true, IMO. In C++ the most significant difference between
namespaces and classes is that namespaces are open, and classes are
shut.

There are others: you can't instantiate a namespace.
Meaning that you can always add things to an already defined namespace, but
you can not add anything to an existing class (unless you happen to have the
source code of that class). In contrast, Ruby classes are always open, you
can always add things to them, etc. , so in that way Ruby classes are like
C++ namespaces. IMO if you want to achieve C++-like namespaces in Ruby,
you'd be best off by using a Ruby class. A Ruby class also comes closer to
a C++ namespace than a Ruby module because a Ruby class can contain
instances of objects, and as far as I know this isn't possible in a Ruby
module.
=> "bar"

I beg to differ: first, your statement isn't true (if I understood you
correctly). Second, modules are not meant to be instantiated directly,
which is the same with C++ namespaces.

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
arinsharma
Top