Graham Slick Graham Slick - 6 months ago 15
Ruby Question

Variable assignment inside of ruby methods

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.

Answer

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.