Bug #14251

String insert changing value of other string

Added by ricardovsilva (Ricardo Silva) over 2 years ago. Updated over 2 years ago.

Target version:
ruby -v:
2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]


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 = foo
bar.insert(1, 'd')
puts foo #aaa
puts bar #adaa

Updated by phluid61 (Matthew Kerwin) over 2 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 ricardovsilva (Ricardo Silva) over 2 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

puts foo #cba
puts bar #cba

Is that correct?

Updated by dsferreira (Daniel Ferreira) over 2 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 2 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.

Also available in: Atom PDF