2014-05-15 4 views
1

여기에 내가 뭘 내용은 다음과 같습니다상속 클래스 변수는 어떻게 만들 수 있습니까?

$ cat 1.rb 
#!/usr/bin/env ruby 
class A 
    @a = 1 
    @@b = 2 
    def self.m 
     p @a 
     p @@b 
    end 
end 
class B < A 
end 
class C < A 
    @@b = 3 
end 
B.m 
$ ./1.rb 
nil 
3 

내가 12를 볼 것으로 예상. 나는 왜 그리고 어떻게해야합니까? 귀하의 질문에 당신을 도움이 될 것입니다

+1

특히 상속과 관련된 경우 클래스 변수를 피하십시오. 이 문제에 대한 오래된 (그러나 여전히 훌륭한) 읽기이며 클래스 인스턴스 변수를 승격합니다. http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/ –

답변

2

이 다른 게시물 :

클래스 변수는 서브 클래스에 의해 액세스 할 수 있지만 클래스 개체에 바인딩 인스턴스 변수는 아니다.

class A 
    @a = 1 # instance variable bound to A 
    @@b = 2 # class variable bound to A 
end 

class B < A; end # B is a subclass of A 

# B has access to the class variables defined in A 
B.class_variable_get(:@@b) # => 2 

# B does not have access to the instance variables bound to the A object 
B.instance_variable_get(:@a) # => nil 

클래스 개체에 바인딩 된 인스턴스 변수를 '클래스 인스턴스 변수'라고도합니다.

+0

'Lee Jarvis'의 [link] (http : // www. railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/)이 유용 할 것입니다. –

관련 문제