Variable/reference question


I feel stupid for having to ask this, but I have never run into this

I have this code that should send an email when someone upgrades their
account. I am using this code:

new_plan = Plan.find(params[:customer][:plan_id])
previous_plan = @customer.plan
@customer.billing_id, @customer.start_date) # if new_plan.price >

The problem is an email never gets send, because new_plan.price is
always equal to previous_plan.price, so it apparently previous_plan
holds a reference to the customer’s plan and when I change that,
previous_plan changes too.

When I change: previous_plan = @customer.plan
to: previous_plan = Plan.find(@customer.plan_id)

it does work, but it feels like I don’t need the extra find…

How would you guys do this?


Yes, previous_plan is a reference to @customer_plan and so changes
with it. Instead of

previous_plan = @customer.plan

This should work with something like

previous_plan = @customer.plan.dup

Which makes previous_plan a copy rather than a reference.

Though not a huge deal, this to me is one of the more annoying and
confusing bits of Ruby. It uses references in many places where I’d
think it would just copy values. And the difference between dup and
clone is poorly documented or mysterious or both.