Graham Slick Graham Slick - 1 year ago 83
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"

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
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
, I get the same result for the first two, and true for the last one.

How is this possible ? I assigned to
the value of
before updating it. And then,
has the same value as
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download