Consider the following code:
class Dog
attr_accessor :name, :color
def initialize(name, color)
end
end
Within a Ruby object, is the convention to access the instance variable directly (ie @name = name) or to use the setter/getter methods (ie name = name)?
The former is more clear to me, but if you implement your own setter/getter methods (eg to increment a class variable at the same time) then you end up having to use both approaches (ie @name = name ; color = color).
What’s the convention within the Ruby community? How should I write my code to make it clear to others who will read it?
Using
name = valueis an error, because that creates a local variable namedname. You must useself.name = value.As for convention, you can only get away with using
@nameif you can guarantee that the accessors will always be lightweightattr_accessors. In all other cases, using@nameoverself.namewill violate encapsulation and give yourself a headache. You gave the exact reason in your question — if there is extra logic in the getter/setter, you must duplicate it if you access the instance variable directly.