0

AFAIK I know these two ways of namespacing in ruby:

module Cat
  class Lion
    def hunt
      p 'roaming for prey ...'
    end
  end

  class Cheetah
    def hunt
      Lion.new.hunt
      p 'Oops there is a lion. Hide first ...'
    end
  end
end

class Cat::MountainLion
  def hunt
    Lion.new.hunt
    p 'roaming for prey ... (since I dont live in the same continent as lion)'
  end
end

Cat::Cheetah.new.hunt
Cat::MountainLion.new.hunt

Why is it the Cat::MountainLion.new.hunt doesn't work? Are namespace declared as module differs to those declared as prefix to class class Cat::?

Willy
  • 9,681
  • 5
  • 26
  • 25

1 Answers1

1

These two ways differ in the constant lookup. The former looks for Lion constant in Cat namespace, which is correct. The latter looks for ::Lion, in global namespace, which is obviously incorrect, since you don't have such constant.

For more information about this topic, please visit this page: https://cirw.in/blog/constant-lookup.html

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
  • 3
    The former looks for `Lion` in `Cat::Cheetah`, then in `Cat` and finally at the top-level. Whereas the latter looks in `Cat::MountainLion` and then at the top-level, thus skipping `Cat`. – Stefan Jun 20 '18 at 09:25