2010-05-28 2 views
1

우리는 다음 코드를 작성하여 실행하려고합니다.Ruby의 유창한 인터페이스 프로그램

class Numeric 
def gram 
self 
end 
alias_method :grams, :gram 

def of(name) 
    ingredient = Ingredient.new(name) 
    ingredient.quantity=self 
    return ingredient 
    end 
end 


class Ingredient 
     def initialize(n) 
     @@name= n 
     end 

     def quantity=(o) 
     @@quantity = o 
     return @@quantity 
    end 

    def name 
     return @@name 
    end 

    def quantity 
     return @@quantity 
    end 

    end 

e= 42.grams.of("Test") 
a= Ingredient.new("Testjio") 
puts e.quantity 
a.quantity=90 
puts a.quantity 
puts e.quantity 

우리는에 직면하는 문제는 객체가 다른 경우에도

puts a.quantity 
puts e.quantity 

의 출력이 동일하다는 것이다. 우리가 관찰 한 것은 두 번째 객체, 즉 'a'가 첫 번째 객체의 값, 즉 'e'를 대체한다는 것입니다. 출력은

42 
90 
90 

로 나오고 있지만, 필요한 출력은

입니다
42 
90 
42 

사람이 왜 일어나고 제안 할 수 있습니다? 객체 ID가 다르기 때문에 객체를 대체하지 않습니다. 객체의 값만 대체됩니다.

답변

3

문제는 인스턴스 변수 @quantity 대신 클래스 변수 @@quantity을 사용하고 있다는 것입니다. 클래스 중 하나만이Ingredient이므로 변수가 인스턴스간에 공유됩니다. 추가 @ 기호를 제거하면 예상대로 작동합니다. 인스턴스 당 @quantityIngredient입니다.

http://www.techotopia.com/index.php/Ruby_Variable_Scope#Ruby_Class_Variables

편집 참조 : 여기 당신이 접근을 작성하지 저장 성분을보다 간결 버전입니다. quantity`와`attr_reader : 당신은 수량과 이름을 인스턴스 변수에 대한 accesors를 사용하는 경우

class Ingredient 
    attr_accessor :quantity, :name 

    def initialize(n) 
    @name = n 
    end 
end 
+0

또한, 당신은 단지'attr_accessor 정의 할 수 있습니다 name'을 전혀 방법을 생략합니다. – Chubas

+0

사실을 반영하기 위해 편집되었습니다. –

+0

오 .. 정말 고마워. 우린 그걸 알아 채지 못했어. 그냥 루비로 시작 했어. – intern

관련 문제