在Ruby中,模块中定义的类如何知道模块的常量? [英] In Ruby, how does a class defined in a module know the module's constants?

查看:70
本文介绍了在Ruby中,模块中定义的类如何知道模块的常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解模块中定义的类如何知道模块的常量.这是我的意思的示例:

I'm trying to understand how a class defined in a module knows the module's constants. Here's an example of what I mean:

module Car
  class Wheel
  end

  class Seat
    p Wheel        # Car::Wheel
  end
end

我知道这很明显,但是由于Wheel在Seat的层次结构中不存在,所以我不知道它如何访问它.

I know it's obvious, but since Wheel is nowhere in Seat's hierarchy, I don't understand how it can have access to it.

推荐答案

如果您引用一个类常量,则Ruby将首先在同一模块中查找它,然后在根目录中找不到它.

If you reference a class constant, Ruby will look for it first in the same module, and then on the root if it's not found there.

因此,由于SeatWheel都在Car模块中,因此,如果要查找Wheel,它将先查找Car::Wheel,然后再查找::Wheel.由于Car::Wheel存在,因此您可以获得该引用.

So, since both Seat and Wheel are in the Car module, if you look for Wheel, it will first look for Car::Wheel, and then for ::Wheel. Since Car::Wheel exists, you get that reference.

这篇关于在Ruby中,模块中定义的类如何知道模块的常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆