首页 > 解决方案 > Different Ways of Namespacing in Ruby

问题描述

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::?

标签: rubynamespaces

解决方案


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


推荐阅读