本帖最后由 寒冷魔王 于 2016-9-6 21:39 编辑
原先给Chd114神查过一个离奇Bug(见下面的func2)
class A def initialize @x = 0 end def x=(e) @x = e end def x @x end # 注:attr_accessor :x 同理 def func0 self.x = 5 end def func1 x = 5 end def func2 p x if false x = 5 end p x end end puts("--0--") a0 = A.new a0.func0 p a0.x puts("--1--") a1 = A.new a1.func1 p a1.x puts("--2--") a2 = A.new a2.func2
class A
def initialize
@x = 0
end
def x=(e)
@x = e
end
def x
@x
end
# 注:attr_accessor :x 同理
def func0
self.x = 5
end
def func1
x = 5
end
def func2
p x
if false
x = 5
end
p x
end
end
puts("--0--")
a0 = A.new
a0.func0
p a0.x
puts("--1--")
a1 = A.new
a1.func1
p a1.x
puts("--2--")
a2 = A.new
a2.func2
Ruby语言十分灵活,有很多匪夷所思的陷阱。很多时候需要通过限制灵活性来减少Bug。比如在类内使用self.调用属性方法(如x, x=)。
另外,像这种名称遮掩在其他语言中也很常见吧,比如
class A { public: void setX(int x) { this->x = x; // 这种赋值的方法如果要同名的话一般加this。 } private: int x; };
class A
{
public:
void setX(int x) {
this->x = x; // 这种赋值的方法如果要同名的话一般加this。
}
private:
int x;
};
|