0

Let's consider the following example:

class Car < ActiveRecord::Base

  def engine
    @engine ||= Engine.new(self)
  end

end

class Engine

  def initialize(vehicle)
    @vehicle = vehicle
  end

  def model
    @vehicle.model
  end

end

and what I don't understand is that when I go to the console and do something like that:

car = Car.last
car.engine.model  # => 'V8'

and then

car.model = 'V6'

I get

car.engine.model  # => 'V6'

It's obviously a simplified example but anyway, can anyone explain why I get a different engine model name in the last line of code? Isn't it supposed to use the @engine variable and return the previous engine model name?

1 Answer 1

1

No surprise here. You initialize Engine instance with car object, so @vehicle instance variable have reference to the same object as car local variable. No wonder then that if you modify car object, @engine object will be modified in the same way.

Sign up to request clarification or add additional context in comments.

2 Comments

I see, thank you. Is engine method safe the way I implemented it or it's better to create a new instance of engine with every call just to make sure that I always get the correct information in case some of the car attributes change?
@JustMichael it's no difference at this aspect. If you instantiate Engine every time you call Car#engine method, it would still return changed Car attributes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.