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.

···

--
Posted via http://www.ruby-forum.com/.

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

···

On Mon, Jan 6, 2014 at 11:27 PM, Joel Pearson <lists@ruby-forum.com> wrote:

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.

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

Hi,

Joel Pearson 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

···

--
Posted via http://www.ruby-forum.com/\.

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

···

--
Posted via http://www.ruby-forum.com/.