matt wrote:
Hello,
I'm browsing through some code, trying to familiarize myself with the
language (I have a C++ background, with only a #include), and I realize
that there are 3 calls that I'm trying to wrap my head around.
Here's my stab:
Require -- seems to include another file to gain access to other
classes, modules, and global data. This seems to be equivalent to a C++
include, with inclusion guards
Load -- seems to be the same as require, but will actually reload the
data every time it is called, where require will load once and cache the
file. This seems to be equivalent to C++ include, with out inclusion
guards.
You got the point. There's a difference however, as you're including
directly the code and not the header as is done usually in C++.
Basically, you'll only ever need to use require, unless you need some
special kind of interaction with the (programmer-)user.
Include -- seems to include a module name from a pre-determined path,
but not classes (unless encapsulated within a module). Would this be
similar to a C++ namespace being given the include directory at compile
time?
I don't really understand what you mean about the include directory.
Module serves two purposes: namespace separation and mixins. Mixins are
Ruby's version of multiple inheritance: whereas C++ authorize multiple
parents for classes, Ruby forbids this, but provides a mechanism for
classes that share common capabilities to share code as well. Let's make
this more explicit:
Array is a descendant of Object, as are all Ruby classes. Hash is also
a descendant of Object. But both share some common capabilities, such as
they all provide a collection of Objects you might like to go through.
This is where modules come in: both include the Enumerable module, which
provides facilities to traverse collections of objects.
In C++, the design would be different:
class Object {};
class Enumerable {};
class Hash: public Object, Enumerable {};
class Array: public Object, Enumerable {};
In ruby,
class Array
include Enumerable
end
class Hash
include Enumerable
end
There you go.
So a couple of things here, are my understandings of the 3 methods
close, if not, could someone please expand on them. The other is what's
the advantage of include vs require? I mean, why would I include a
module, rather than require it's filename?
You need to require the filename first so that the module is
available. Then, you can include it in classes if you need their
functionality.
Cheers,
Vince
···
--
Vincent Fourmond, PhD student
http://vincent.fourmond.neuf.fr/