aiuchi aiuchi - 3 months ago 11
Ruby Question

Require statement usage in ruby

Is there any difference between these two sample Ruby programs? It seems the same.

require
just includes the Ruby program on memory.

require_sample1.rb

class Klass
require "./effective_module"
include Mod
end


require_sample2.rb

require "./effective_module"
class Klass
include Mod
end


effective_module.rb

module Mod
end

Answer

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_sample.rb
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)

This time 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.

Comments