Ruby constant lookup for classes in modules

  • Thread starter Jack Christensen
  • Start date
J

Jack Christensen

What's the difference between defining a class inside of a module and
using the module as a prefix?

module Foo
class Bar
end
end

module Foo
class Works
def f
Bar.new
end
end
end

class Foo::Fails
def f
Bar.new
end
end

Foo::Works.new.f
Foo::Fails.new.f


The last line fails:

lookup.rb:16:in `f': uninitialized constant Foo::Fails::Bar (NameError)
from lookup.rb:21

I would have thought that both ways of placing a class in a module would
be equivalent.

Thanks.

Jack
 
P

Peter

  What's the difference between defining a class inside of a module and
using the module as a prefix?

module Foo
   class Bar
   end
end

module Foo
   class Works
     def f
       Bar.new
     end
   end
end

class Foo::Fails
   def f
     Bar.new
   end
end

Foo::Works.new.f
Foo::Fails.new.f

The last line fails:

lookup.rb:16:in `f': uninitialized constant Foo::Fails::Bar (NameError)
     from lookup.rb:21

I would have thought that both ways of placing a class in a module would
be equivalent.

Thanks.

Jack

Hi Jack,

I believe the difference is one of scope:

module Foo
class Works

means "put Works in the namespace of Foo" and "define Works in the
scope of the module Foo", and hence 'Bar' is accessible.

class Foo::Fails

means, "put Fails in the namespace of Foo" but "define Fails in the
current scope", and hence 'Bar' is not accessible.

Hope that helps,

Peter.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top