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.
This may sound unorthodox in a (essentially imperative) language like Ruby, but my advice is: avoid collateral damages by not updating objects at all (except when strictly necessary); create new ones instead. You pay a bit of performance but you'll get code which is clearer, more compact, more modular and easier to debug.
http://en.wikipedia.org/wiki/Functional_programming
So, in your example, just create a new string with a new name:
complete_name = name + title
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With