• class variables are available in class methods and instance methods, but class instance variable is only available in class methods:
    ruby 代码
    1. class Test    
    2.   @@cla_var = 1    
    3.   @inst_var = 1    
    4.        
    5.   def self.cla_var    
    6.     @@cla_var    
    7.   end    
    8.   def cla_var    
    9.    @@cla_var    
    10.   end    
    11.   def self.inst_var    
    12.     @inst_var    
    13.   end    
    14.     
    15.   def inst_var    
    16.      #here @inst_var is treated as the instance variable not class instance variable    
    17.      @inst_var    
    18.   end    
    19.  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 代码
     
    1. class Parent  
    2.    @@cla_var = 1  
    3.    @inst_var = 2  
    4.      
    5.     def self.cla_var  
    6.         @@cla_var  
    7.     end  
    8.     def self.inst_var  
    9.         @inst_var  
    10.     end  
    11.   
    12.     def self.cla_var=(cla_var)  
    13.         @@cla_var = cla_var  
    14.     end  
    15.     def self.inst_var=(inst_var)  
    16.         @inst_var = inst_var  
    17.     end  
    18.   
    19. end  
    20. class Child1 < Parent  
    21. end  
    22. class Child2 < Parent  
    23. end  
    24.   
    25. #class variables are shared by parent and all the children  
    26. >> Parent.cla_var  
    27. => 1  
    28. >> Child1.cla_var  
    29. => 1  
    30. >> Child2.cla_var  
    31. => 1  
    32. >> Child1.cla_var = 3  
    33. => 3  
    34. >> Parent.cla_var  
    35. => 3  
    36. >> Child2.cla_var   
    37. => 3  
    38.   
    39. #every children has it's own copy of class instance variables  
    40. >> Parent.inst_var  
    41. => 2  
    42. >> Child1.inst_var  
    43. => nil  
    44. >> Child2.inst_var>> Child1.inst_var = 4  
    45. => 4  
    46. >> Parent.inst_var  
    47. => 2  
    48. >> Child2.inst_var  
    49. => nil  
    50.   
    51. => nil  

评论
发表评论

您还没有登录,请登录后发表评论