I've been bitten a couple of times by forgetting that x = y
in Ruby makes x refer to the same object as y; I'm too used to languages where it means, in Ruby terms, x = y.dup
. Forgetting this, I inadvertently change y
when I think it's safe on the right side of the assignment.
I can see that it would make sense to avoid simple x = y
assignments without a special reason, but the same thing can be lurking in other places such as
name = (person.last_name.blank? ? 'unknown' : person.last_name)
where a later name << title
would actually be changing person.last_name and not just name.
If this has happened to you, too, how have you learned to avoid it? Are there certain red flags or patterns to look for? Do you look with suspicion at each assignment you make? Do you use .dup
a lot? I don't know if Ruby's usage will ever become second nature to me, so any useful tips would be welcome.