Is there any difference between these two sample Ruby programs? It seems the same.
With the sample code you've given, the behavior is effectively the same. However, it won't always be the same. For example, take the following code:effective_module.rb
module Foo; end
require "./effective_module" class Foo end
When you run
ruby require_sample.rb you'll get the following error:
require_sample.rb:2:in `<main>': Foo is not a class (TypeError)
This demonstrates to us that on line 2, when
class Foo is reached,
Foo has already been defined (by
effective_module.rb) as a module, and Ruby won't let you redefine a module as a class.
Now suppose we make the following change:require_sample.rb
class Foo require "./effective_module" end
Now when you run
ruby require_sample.rb, you get a different error:
.../effective_module.rb:1:in `<top (required)>': Foo is not a module (TypeError)
Foo is already defined as a
class when the
require is reached. Ruby won't let you redefine a module as a class.
Obviously this isn't the kind of code you'd write in the real world, but hopefully it helps demonstrate that where you put your
requires does matter.