views:

116

answers:

2

All,

I was wondering if anyone has an intermit enough knowledge of rubys 'require' to tell me if the following is valid ruby or not;

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, would the require place the gem into the global namespace as the same require at the top of the file would?

Cheers,

Roja

+7  A: 

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.

Simone Carletti
Fantastic, thats what i wanted to know :)
roja
+3  A: 

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

Chris McCauley
apologies about the spelling ;)
roja
No problem - great question (+1 from me)
Chris McCauley