Do Ruby 'require' statements go inside or outside the class definition?

Solution 1:

Technically, it doesn't really matter. require is just a normal method call, and the scope it's called in doesn't affect how it works. The only difference placement makes is that it will be executed when whatever code it's placed in is evaluated.

Practically speaking, you should put them at top so people can see the file's dependencies at a glance. That's the traditional place for it.

Solution 2:

at the top.

require 'rubygems'
require 'fastercsv'

class MyClass
  # Do stuff with FasterCSV
end

Solution 3:

I can see a possible reason for not putting a require at the top of the file: where it's expensive to load and not always executed. One case that occurs to me is where, for example, code and its tests are in the same file, which is something I like to do from time to time for small library code in particular. Then I can run the file from my editor and the tests run. In this case when the file is required in from elsewhere, I don't want test/unit to be loaded.

Something a little like this:

def some_useful_library_function()
  return 1
end

if __FILE__ == $0
  require 'test/unit'
  class TestUsefulThing < Test::Unit::TestCase
    def test_it_returns_1
      assert_equal 1, some_useful_library_function()
    end
  end
end

Solution 4:

It doesn't really matter where you put them, but if you put them inside a class or module expression, then it looks like you are importing whatever is in the required file into the class's namespace, which is not true: everything ends up in the global namespace (or whatever namespaces are defined in the library).

So, better put them at the top to avoid any confusion.