Ruby的常量在嵌套类与子类中的引用 —— 差异点

时间:2022-10-29 13:42:32
# 嵌套类
class Drawing
PI = 123123
def Drawing.give_me_a_circle
Circle.new
end
def xpi
PI
end

class Line
end
class Circle
def what_am_i
"This is a circle"
end
def pi
PI
end
end
end

# 子类
class SubDrawing < Drawing
end

# 常量在嵌套类与子类的使用: 方法内的常量与类指定的常量
PI = 3.1415926
circle = Drawing.give_me_a_circle
drawing = Drawing.new
subdrawing = SubDrawing.new

print "circle.pi=" , circle.pi , "\n"
print "Drawing::Circle::PI=" , Drawing::Circle::PI , "\n"

print "subdrawing.pi=" , subdrawing.pi , "\n"
print "SubDrawing::PI=" , SubDrawing::PI , "\n"

print "drawing.pi=" , drawing.pi , "\n"
print "Drawing::PI=" , Drawing::PI , "\n"
    

# 输出
class.rb:114: warning: toplevel constant PI referenced by Drawing::Circle::PI
circle.pi=123123 # 方法内引用常量
Drawing::Circle::PI=3.1415926 # 直接嵌套类指明引用常量

subdrawing.pi=123123
SubDrawing::PI=123123
drawing.pi=123123
Drawing::PI=123123

## 说明
直接由类指定的常量引用 —— 必须在类内直接定义才能覆盖程序范围内的常量定义
子类:继承父类的常量定义,即方法内引用于类指明常量时都引用父类的常量定义
嵌套类:在方法内访问时,引用外部类的常量定义; 在嵌套类指明常量时(如:Drawing::Circle::PI),使用程序范围内的常量定义