Ruby Instance Variables and Class Instance Variables

feitian124 · 2013年03月15日 · 最后由 feitian124 回复于 2013年03月15日 · 2593 次阅读

这个必须要吐槽一下,否则记不住。

class Hi
   #self is point to the Hi class object so it became class instance variable
  @class_instance_variable 

   def a_method
      #self is point to the Hi instance so it became instance variable
      @instance_variable
   end
end

虽然早就知道self这挡子事,但自己就是没往这方面想过,所以看到书上指出来,
还是感到很惊讶, 需要将self的认识提高到一个新的高度。继续拜读 《meteprogramming ruby》。

惊讶是因为以前有别的语言的编程经验,没有经验对比就不会惊讶了...

@luikore 还忘记说了一个概念,class variables. 从前看到 @ 开头的就无脑认为是instance variable, 从前看到 @@ 开头的就无脑认为是class variable, 现在知道还有个Class Instance Variables, 而且ruby世界更倾向于使用它~

需要 登录 后方可回复, 如果你还没有账号请 注册新账号