Style for accessing instance vars

Hello everybody,

Given this simple class:

class Person

attr_reader :age, :gender, :sex

def initialize(age, gender, location)

@age = age

@gender = gender

@location = location

end

end

What’s the preferred method to access its variables (assuming they have
a
getter method)

from within its methods? Directly (via @), or indirectly (via the
accessor), i.e.:

def describe

“A #{@age} year old {@gender} who lives in #{@location}”

end

or

def describe

“A #{age} year old {gender} who lives in #{location}”

end

Thank you in advance!

Kind regards,

Simeon

The “best practice” way of doing this is:

self.age = age

self.gender = gender

self.location = location

The reason is pretty straightforward. Say later on you want to alter the
behaviour of your getter or setter, you only need do this in 1 place,
rather than hunting down every mention of the instance variable.

On Mon, Jan 6, 2014 at 11:27 PM, Joel P. [email protected]
wrote:

rather than hunting down every mention of the instance variable.
There is one more reason to do it that way:

Person = Struct.new :age, :gender, :sex do
def describe
“A #{age} year old {gender} who lives in #{location}”
end
end

In other words: Struct does not define instance variables - you can
only access them via accessor methods.

Kind regards

robert

Hi,

Joel P. wrote in post #1132376:

The “best practice” way of doing this is:

self.age = age

self.gender = gender

self.location = location

The reason is pretty straightforward. Say later on you want to alter the
behaviour of your getter or setter, you only need do this in 1 place,
rather than hunting down every mention of the instance variable.

When I need the setter only for the constructor method then defining a
setter for the instance automatically seems to be in violation of YAGNI;
beside this if I want to keep the API of the instance/object strict, I
would have to make those setters private.

My ‘best’ practice is to use the @variable assignment within the
constructor when I don’t want the object to change it during its
life-cycle and to use the setter when I expect the @variable to change
outside of constructor.

vlad

Perfectly valid point, for any read-only attributes you use the instance
var.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs