Forum: Ruby Constant lookup when using namespaces

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
unknown (Guest)
on 2009-01-11 22:35
(Received via mailing list)
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?
Rob B. (Guest)
on 2009-01-11 22:44
(Received via mailing list)
On Jan 11, 2009, at 3:34 PM, removed_email_address@domain.invalid wrote:

> 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
>
> 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 B.    http://agileconsultingllc.com
removed_email_address@domain.invalid
This topic is locked and can not be replied to.