Bug #14251
closedString insert changing value of other string
Description
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 phluid61 (Matthew Kerwin) over 6 years ago
All Ruby variables are by-reference. To create a new object, use #dup
foo = 'abc'
bar = foo.dup
bar.insert(1, 'd')
Updated by shevegen (Robert A. Heiler) over 6 years ago
Here is a blog entry that may be useful for ricardo:
https://aaronlasseigne.com/2014/07/20/know-ruby-clone-and-dup/
Updated by ricardovsilva (Ricardo Silva) over 6 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) over 6 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 +
operation.
Hope this helps.
Ruby talk is the right place for this things.
Welcome to ruby world!
Updated by duerst (Martin Dürst) over 6 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.