0

I have this pretty simple method:

def update_context(msg, session, sender)
    previous_context = session.context 
    session.update(context: intent_determination(msg, session.context, sender))
    session.update(context: brand_determination(msg, session.context))
    session.update(context: style_determination(msg, session.context))
    session.update(context: price_range_determination(msg, session.context))
    session.update(context: size_determination(msg, session.context))
       p previous_context
       p session.context
       p (previous_context == session.context)
    unless session.context.size == 0
      if previous_context == session.context
        session.context["intent"] = "lost"
        session.save
      end
    end
  end

My problem is certainly due to a stupid mistake I can't see but please bear with me on this one, I really can't see it.

As you can see, I "save" the session's context in a previous_context variable at the beginning of the method. Then, I'm running a few updates on the context. However, when I print previous_context, session.context and previous_context == session.context, I get the same result for the first two, and true for the last one.

How is this possible ? I assigned to previous_context the value of session.context before updating it. And then, previous_context has the same value as session.context after I've updated it.

I really can't see where I screwed up here, or there is definitely something I don't understand.

Graham Slick
  • 6,692
  • 9
  • 51
  • 87
  • 1
    Though unrelated to your question, you could write `[:brand_determination, :style_determination, :price_range_determination, :size_determination].each { |m| session.update(context: send(m, msg, session.context)) }`. – Cary Swoveland May 09 '16 at 20:25
  • @CarySwoveland thanks for the input, I appreciate it ! I'll update my code – Graham Slick May 09 '16 at 20:33

2 Answers2

1

previous_context = session.context makes the previous_context variable point to the same object as session.context. If you want to change one without affecting the other, you'll need to create a copy of session.context to store in previous_context.

Tommy Steimel
  • 771
  • 8
  • 16
0

in Ruby, variables are just references to objects, so what you are doing there is merely creating a new reference to the same object. If you wish to save the previous state you will have to copy the entire object.

See this answer for a more graphic explanation.

Community
  • 1
  • 1