What is the best practice in Ruby to avoid misusing the "=" assignment?

I was bitten a couple of times, forgetting that x = yin Ruby, x makes a reference to the same object as y; I'm too used to the language, which means, in the Ruby, x = y.dup. Forgetting it, I inadvertently change yit when I think itโ€™s safe on the right side of the assignment.

I see that it would be wise to avoid simple appointments for x = yno particular reason, but the same thing can be hidden in other places, such as

name = (person.last_name.blank? ? 'unknown' : person.last_name)

where later name << titlewill actually change person.last_name, not just the name.

If this happened to you, how did you learn to avoid this? Are there certain red flags or patterns to search for? Are you looking with suspicion at every task you do? Do you use a .duplot? I donโ€™t know if using Ruby will be second nature to me, so any helpful hints would be welcome.

+3
source share
4 answers

This may sound unorthodox in a (essentially imperative) language such as Ruby, but my advice is to avoid collateral damage by not updating objects at all (unless strictly necessary); create new ones instead. You pay a little performance, but you get code that is more understandable, more compact, more modular, and easier to debug.

http://en.wikipedia.org/wiki/Functional_programming

, :

complete_name = name + title
+5

tokland :

- , , . - , Ruby ( , ), ( , ).

, , :

  • , Ruby: , . , y=x, " y , x".
  • name << title name.
  • name += title name title, name. .
+1

, , , . -

hash = {....}
filename = object.file_name
hash.each |k, v| {file_name.gsub!(k, v) if file_name.include? k}

, , file_name โ€‹โ€‹ . object.file_name , file_name.gsub!. . .gsub! file_name = file_name.gsub, file_name = object.file_name.dup. .

I think we should be careful with methods that have !and <<, since they modify the original object on which they act, especially after such assignments.

0
source

A method should not change a variable (for example, using a shift operator) unless its definition indicates that it will change it.

So: never modify an object in a method that has not created (a) it, or (b) the document that it modifies.

0
source

All Articles