What is the best way to invoke inhirited instance method within constructor?

The question is as of the title. Say I have a simple example below:

class Vehicle
attr_accessor :wheels
end

class Car < Vehicle
def initialize
self.wheels = 4
end
end

class Truck < Vehicle
def initialize
@wheels = 16
end
end

I am curious which way is considered correct or better to invoke
wheels writer method of mother Vehicle?

On Fri, Sep 30, 2011 at 3:46 AM, Jones L. [email protected] wrote:

end
end

class Truck < Vehicle
def initialize
@wheels = 16
end
end

I am curious which way is considered correct or better to invoke
wheels writer method of mother Vehicle?

Truck#initialize does not invoke any writer method at all but plain
assigns an instance variable @wheels. If you have a writer method
then it is generally considered much more robust to use it (like you
did in Car#initialize) because the writer might do more than to just
assign to a local variable (e.g. validity checks which ensure the
value is an integer value and greater or equal to 0).

Kind regards

robert

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