Constant lookup when using namespaces

N

nemlet

Here is an example.

#!/usr/bin/ruby

class A

end

class A::B

def method_one
x = C.new
puts x.blah
end

end

class A::C

def blah
puts "I want this one"
end
end

class C

def blah
puts "this is the wrong one"
end

end

ab = A::B.new
ab.method_one




As you can see when you run it you get the blah out of ::C NOT A::C
which I was expecting. Is there a way to be able to say C.new inside
of A::B and have it check the A:: Namespace first?
 
R

Rob Biedenharn

Here is an example.

#!/usr/bin/ruby

class A

end

class A class B

def method_one
x = C.new
puts x.blah
end
end


end

class A class C

def blah
puts "I want this one"
end end

end

class C

def blah
puts "this is the wrong one"
end

end

ab = A::B.new
ab.method_one




As you can see when you run it you get the blah out of ::C NOT A::C
which I was expecting. Is there a way to be able to say C.new inside
of A::B and have it check the A:: Namespace first?

I don't remember the details of "why", but "class A::C; end" opens the
A:: scope differently from "class A; class C; end; end". When you
make the "class A" namespace explicit, you get the behavior you were
expecting.

-Rob

Rob Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 

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,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top