우리는 다음 코드를 작성하여 실행하려고합니다.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가 다르기 때문에 객체를 대체하지 않습니다. 객체의 값만 대체됩니다.
또한, 당신은 단지'attr_accessor 정의 할 수 있습니다 name'을 전혀 방법을 생략합니다. – Chubas
사실을 반영하기 위해 편집되었습니다. –
오 .. 정말 고마워. 우린 그걸 알아 채지 못했어. 그냥 루비로 시작 했어. – intern