2010-05-13 6 views
1

나는 Ruby를 연구 중이며 뇌는 그냥 얼어 붙었다.Ruby에서 클래스 변수에 대한 작성기 메소드를 작성하려면 어떻게해야합니까?

다음 코드에서 'self.total_people'에 대한 클래스 작성기 메서드를 작성하는 방법은 무엇입니까? 저는 'Person'클래스의 인스턴스 수를 '계산'하려고합니다. 좀 더 정확하게 total_people 정의 할 수 current_people

def self.total_people=(v) 
    @@total_people = v 
end 

당신은 @@의 모든 인스턴스를 옮기고 :

class Person 

    attr_accessor :name, :age 

@@nationalities = ['French', 'American', 'Colombian', 'Japanese', 'Russian', 'Peruvian'] 

@@current_people = [] 

@@total_people = 0 

def self.nationalities #reader 
    @@nationalities 
end 

def self.nationalities=(array=[]) #writer 
    @@nationalities = array 
end 

def self.current_people #reader 
    @@current_people 
end 

def self.total_people #reader 
    @@total_people 
end 

def self.total_people #writer 
    #-----????? 
end 



def self.create_with_attributes(name, age) 
    person = self.new(name) 
    person.age = age 
    person.name = name 
    return person 
end 


def initialize(name="Bob", age=0) 
    @name = name 
    @age = age 
    puts "A new person has been instantiated." 
    @@total_people =+ 1 
    @@current_people << self 
end 

답변

6

당신은 등호 메소드 이름의 끝에 서명을 추가하여 하나를 정의 할 수 있습니다

def self.total_people 
    @@current_people.length 
end 

모든 @@ total_people 관련 코드를 제거하십시오.

module PersonClassAttributes 
    attr_writer :nationalities 
end 

class Person 
    extend PersonClassAttributes 
end 

내가 attr_writer 어떤 이유로 모듈 작동하지 않기 때문에이 용의자 : 작동하지 않았다

0

한 가지 방법은 다음이었다.

내가 접근하고 싶은 메타 프로그래밍 방식이 있는지 알고 싶습니다. 그러나 사람들 목록이 포함 된 개체를 만드는 것을 고려 했습니까? - 클래스 VAR의 부모의 값을 재정의 할 수 없습니다 하위 클래스

class Person 
    class << self 
    attr_accessor :foobar 
    end 

    self.foobar = 'hello' 
end 

p Person.foobar # hello 

Person.foobar = 1 

p Person.foobar # 1 

이 상속 루비의 클래스 변수와 개는 유의하십시오

4

나는이 방법으로 문제가 해결 생각합니다. class instance variable이 실제로 원하는 것일 수 있으며,이 솔루션은 그 방향으로 나아갑니다.

관련 문제