Question

Does anyone know enough about Ruby's require to tell me if the following is valid syntax:

class Something

  def initialize(mode)
     case mode
     when :one then require 'some_gem'
     when :two then require 'other_gem'
     end
  end

end

s = Something.new

If so, will the require place the gem into the global namespace as it would when at the top of the file?

Was it helpful?

Solution

If so, would the require place the gem into the global namespace as the same require at the top of the file would?

Yes. require doesn't have scope, while load does.

OTHER TIPS

Yes it's perfectly valid and works as expected because require isn't scoped

Require pulls in the code from the specified file and attempts to use it in-place - that might mean that it isn't sensible to do but yes it can be done.

The local method scope would be unaffected and any class definition etc would be at the expected scope

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top