2013-08-29 2 views
1

자바에서는 클래스의 공용 멤버를 선언 할 수 있지만 Ruby에서는이를 수행 할 수 없습니다.Ruby 클래스 멤버를 선언 할 수 있습니까?

class Person 
    @a = 1 

    def hello() 
    puts(@a) 
    end 
end 

p = Person.new 
p.hello() 
#nil 

왜 출력 nil보다는 1입니까?

+0

다음은 클래스 및 인스턴스 변수에 대한 설명입니다. http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/ –

답변

1

인스턴스 변수 @a가 인스턴스 pr에 대해 초기화되지 않았기 때문에.

class Person 
@a = 1 
    def hello() 
    puts(@a) 
    end 
end 

pr = Person.new 
pr.instance_variable_get(:@a) # => nil 

지금 아래 참조 : -

class Person 
    def initialize(a) 
    @a=a 
    end 
    def hello() 
    puts(@a) 
    end 
end 

pr = Person.new(1) 
pr.instance_variables # => [:@a] 
Person.instance_variables # => [] 
pr.instance_variable_get(:@a) # => 1 
pr.hello # => 1 

Instance variables

인스턴스 변수는 @로 시작하는 이름을 가지고 있으며, 그 범위를 의미 어떤 목적 자체에 국한된다. 두 개의 서로 다른 객체는 동일한 클래스에 속해 있더라도 인스턴스 변수에 대해 다른 값을 가질 수 있습니다. 객체 외부에서, 인스턴스 변수는 프로그래머가 명시 적으로 제공하는 메소드를 제외하고는 변경되거나 관찰 (즉, 루비의 인스턴스 변수는 공개되지 않습니다) 할 수 없습니다. 전역 변수와 마찬가지로 인스턴스 변수는 초기화 될 때까지 nil 값을 갖습니다.


이제 이쪽을 봐 : -

class Person 
@a = 1 
    def self.hello() 
    puts(@a) 
    end 
end 
Person.hello # => 1 
Person.instance_variables # => [:@a] 
Person.new.instance_variables # => [] 

그래서이 예제 @a 객체 Person의 인스턴스 변수에 Person .Very 좋은 팁의 경우는 여기에 없습니다 - Class Level Instance Variables.

+0

선언 할 때 초기 인스턴스 변수? – user2730388

+0

각 개체는 인스턴스 변수의 자체 복사본을 가지고 있습니다. –

+0

완벽하게 이해했습니다. 상세한 답변을드립니다! – user2730388

관련 문제