[ruby-list:37834] Re: reference from nested class to a constant in a module included by the parent class

From: NISHIMATSU Takeshi <t-nissie@...>
Date: 2003-06-27 19:44:04 UTC
List: ruby-list #37834
西松です.

[ruby-list:37831] で まつもとさん:
>あるクラスから見える定数は
>
>  自分で定義されたもの
>  その外側のクラスで定義されたもの
>  そのまた外側で定義されたもの(以下トップレベルまで続く、トップレベル含まない)
>  スーパークラスで定義されたもの
>  そのスーパークラスで定義されたもの(以下Objectまで続く、Object含まない)
>
>です。外側のクラスにincludeされているモジュールで定義されて
>いる定数はこの条件に合致しませんので直接参照できません。

お返事をありがとうございます. この場合,
下の例の★はどの条件に合致していると考えればよいのでしょうか.
★で直接参照できるので, ネストしたクラスの中からも
直接参照できそうだと考えてしまいました.

# incmod.rb
module M
  ConstM = "M"
end
class Parent
  ConstP = "P"
  include M
  p ConstP        # => "P"
  p M::ConstM     # => "M"
  p ConstM        # => "M" ★
  class Nested
    p ConstP      # => "P"
    p M::ConstM   # => "M"
    #p ConstM     # => uninitialized constant Parent::Nested::ConstM (NameError)
  end
end
p Parent::ConstP     # => "P"
p Parent::M::ConstM  # => "M"
p Parent::ConstM     # => "M"
p M::ConstM          # => "M"
#p ConstM            # => uninitialized constant ConstM (NameError)

include Math
p PI              # => 3.14  トップレベルでincludeしたmodule中の定数
ConstT = "Top"
class C
  p PI            # => 3.14  トップレベルでincludeしたmodule中の定数
  p ConstT        # => "Top" トップレベルで定義した定数
  class Cn
    p PI          # => 3.14  トップレベルでincludeしたmodule中の定数
    p ConstT      # => "Top" トップレベルで定義した定数
  end
end


-- 
 love && peace && free_software
 西松 毅

In This Thread