---
title: "\"class instance variable\" 和 “class variable”的区别"
author: "sean"
date: "2007-10-20T17:18:49Z"
tags: []
slug: "class-instance-variable-class-variable"
draft: false
lastmod: "2007-10-20T17:18:49Z"
id: 133827
url: "https://sean.iteye.com/blog/133827"
---

- class variables are available in class methods and instance methods, but class instance variable is only available in class methods:
  
  ruby 代码
  
  01. class Test
  02. @@cla\_var = 1
  03. @inst\_var = 1
  04. def self.cla\_var
  05. @@cla\_var
  06. end
  07. def cla\_var
  08. @@cla\_var
  09. end
  10. def self.inst\_var
  11. @inst\_var
  12. end
  13. def inst\_var
  14. #here @inst\_var is treated as the instance variable not class instance variable
  15. @inst\_var
  16. end
  17. end
- Class variables are shared by children of the class in which they are first defined, but  class instance variables not, every child has it's own copy of class instance variable(Rumor has it that ruby1.9 will change this).
  
  ruby 代码
  
   
  
  01. class Parent
  02. @@cla\_var = 1
  03. @inst\_var = 2
  04. def self.cla\_var
  05. @@cla\_var
  06. end
  07. def self.inst\_var
  08. @inst\_var
  09. end
  10. def self.cla\_var=(cla\_var)
  11. @@cla\_var = cla\_var
  12. end
  13. def self.inst\_var=(inst\_var)
  14. @inst\_var = inst\_var
  15. end
  16. end
  17. class Child1 &lt; Parent
  18. end
  19. class Child2 &lt; Parent
  20. end
  21. #class variables are shared by parent and all the children
  22. &gt;&gt; Parent.cla\_var
  23. =&gt; 1
  24. &gt;&gt; Child1.cla\_var
  25. =&gt; 1
  26. &gt;&gt; Child2.cla\_var
  27. =&gt; 1
  28. &gt;&gt; Child1.cla\_var = 3
  29. =&gt; 3
  30. &gt;&gt; Parent.cla\_var
  31. =&gt; 3
  32. &gt;&gt; Child2.cla\_var
  33. =&gt; 3
  34. #every children has it's own copy of class instance variables
  35. &gt;&gt; Parent.inst\_var
  36. =&gt; 2
  37. &gt;&gt; Child1.inst\_var
  38. =&gt; nil
  39. &gt;&gt; Child2.inst\_var&gt;&gt; Child1.inst\_var = 4
  40. =&gt; 4
  41. &gt;&gt; Parent.inst\_var
  42. =&gt; 2
  43. &gt;&gt; Child2.inst\_var
  44. =&gt; nil
  45. =&gt; nil