then only foo becomes “ellooo” while bar remains “ello”
Why is bar independent of foo in the second case, but not the first?
Thanks,
Alex
The line
bar = foo
doesn’t create a copy of foo but simply stores in bar the same object
which is
already stored in foo (if you look at the object_id of foo and bar,
you’ll see
they’re equal). Since delete! modifies its receiver in place, you see
the
changes also when you access the object using bar, not only when using
foo.
The String#+ operator, instead, doesn’t modify its receiver in place,
but
returns a new string, which contains the characters of the first one
concatenated with those of the second one. So, after
foo = foo + “oo”
the object (string) contained in foo is different from the one contained
in
bar and subsequent changes to the object stored in foo don’t affect bar
at
all.
If you truly need that bar and foo contain two different strings with
the same
contents, you can use String#dup:
bar = foo.dup
This behavior is not exclusive of strings, but is a feature of the ruby
language. This means that you may need to be careful when passing
objects
which allow in-place modifications.