String insert changing value of other string
foo = 'abc' bar = foo bar.insert(1, d) puts foo 'adbc' puts bar 'adbc'
The example above should only affect bar variable. It leads to an error by programmer.
A bypass that I found is to do:
foo = 'aaa' bar = String.new foo bar.insert(1, 'd') puts foo #aaa puts bar #adaa
Updated by shevegen (Robert A. Heiler) about 3 years ago
Here is a blog entry that may be useful for ricardo:
Updated by ricardovsilva (Ricardo Silva) about 3 years ago
Because if you do
foo = 'aaa' bar = foo bar = bar + 'ccc' #here references of foo doesn't changes puts foo #aaa pubs bar #aaaccc
As I can see, ruby only for string as reference when I call string methods, like:
foo = 'abc' bar = foo bar.reverse! puts foo #cba puts bar #cba
Is that correct?
Updated by dsferreira (Daniel Ferreira) about 3 years ago
I advise you to put this “issues” you find as questions in ruby talk before opening ruby core bugs.
In ruby objects are mutable and passed by reference.
When you do
bar = bar + 'ccc'
you are allocating a new reference to bar object. The output object of the
Hope this helps.
Ruby talk is the right place for this things.
Welcome to ruby world!
Updated by duerst (Martin Dürst) about 3 years ago
- Status changed from Open to Rejected
This behavior is expected. Except for purely functional programming languages, the difference between references and values is important to understand in every programming language, even if at first, it may be surprising.