Why Include and Require?

HI All,

with our volunteer teacher absent last night, our class was left to
ponder
things for ourselves. We were looking at a ruby equivalent for cp and
came
upon something that we all didn’t understand. In the below code, small
as it
may be,

#!/usr/local/bin/ruby

require ‘fileutils’
include FileUtils::Verbose
cp(“methround.rb”, “newmethround.rb”)

we wondered why we required to use require and include before the code
would
work. Naturally, if we removed the, “::Verbose” it still worked. Why
require
and then include fileutils? Cheers.

Mark S…

On 6/28/06, Mark S. [email protected] wrote:

include FileUtils::Verbose
cp(“methround.rb”, “newmethround.rb”)

we wondered why we required to use require and include before the code would
work. Naturally, if we removed the, “::Verbose” it still worked. Why require
and then include fileutils? Cheers.

Mark S…

require loads the files, include includes a module in to a class.

In this case you’re including FileUtils::Verbose in to the Object
class. Removing Verbose works as FileUtils also includes cp, but
::Verbose uses the Verbose version of cp.

require brings in the code so that you could do something like

FileUtils::Verbose::cp(“methround.rb”, “newmethround.rb”)

include allows you to write something without the namespace (module in
ruby)
in front of it hence being able to write:

cp(“methround.rb”, “newmethround.rb”)

This has a good explanation especially if you come from a java
background:

http://cwilliams.textdriven.com/articles/2006/04/20/namespacing-and-scoping-in-ruby

Cheers,
Jon W.