There's a convention to reference an object's attributes over its instance variables, where possible. Practical Object-Oriented Design in Ruby says:
Always wrap instance variables in accessor methods instead of directly referring to variables...
This is shown with an example, which I've paraphrased:
class Gear
attr_reader :chainring, :cog
...
def ratio
# this is bad
# @chainring / @cog.to_f
# this is good
chainring / cog.to_f
end
The most common way I see to create a new object with an instance variable is this:
class Book
attr_accessor :title
def initialize(title)
@title = title
end
end
@title=
directly accesses the instance variable title
. Assuming we are following the the 'attribute over instance variable' convention, is it more appropriate to use self.title=
, which would tell the object to send itself the message title=
, thereby using the attribute write method, over the instance variable directly?
class Book
attr_accessor :title
def initialize(title)
self.title = title
end
end
The book talks about 'attribute over instance variable' with reference to reading an instance variable, but doesn't it also apply to writing?