가능한 경우 인스턴스 변수를 통해 객체의 속성을 참조하는 규칙이 있습니다. Practical Object-Oriented Design in Ruby는 말한다 :object.initialize에서 자체를 사용하는 것이 더 좋습니다. @ 이상?
항상 접근 방법 대신 직접 변수를 참조 인스턴스 변수를 래핑 ...
이
내가 의역 한 예와 같습니다class Gear
attr_reader :chainring, :cog
...
def ratio
# this is bad
# @chainring/@cog.to_f
# this is good
chainring/cog.to_f
end
인스턴스 변수를 사용하여 새 객체를 만드는 가장 일반적인 방법은 다음과 같습니다.
class Book
attr_accessor :title
def initialize(title)
@title = title
end
end
@title=
은 인스턴스 변수 title
에 직접 액세스합니다. 우리가 '인스턴스 변수를 통한 속성'규약을 따르고 있다고 가정하면 self.title=
, which would tell the object to send itself the message title=
을 사용하여 속성 쓰기 메소드를 인스턴스 변수에 직접 사용하는 것이 더 적절합니까?
class Book
attr_accessor :title
def initialize(title)
self.title = title
end
end
인스턴스 변수를 읽고 참조하여 '인스턴스 변수를 통해 속성'에 대한 책 회담, 그러나 또한 쓰기에 적용되지 않습니다?
어떤 경우에는'self.feature ='가'@ feature ='보다 더 선호되는데, 일반적으로'self.' 쉘에 할당 할 때 더 많은 actiona를 수행하고 단지 할당 만하면됩니다. 두 번째로, https://github.com/3aHyga/ruby-style-guide에서 좋은 스타일 인'self.feature ='는 복잡한 할당 (한 번에 인스턴스 변수)가 발생합니다. 읽기의 경우'feature == "value"'와 같이 항상 사용되는 구조 –