Stefano Crocco
7/12/2008 7:10:00 PM
On Saturday 12 July 2008, Alex DeCaria wrote:
> I am confused by the use of the delete! method as applied to a string.
> In IRB if I type
>
> foo = "hello"
> bar = foo
> foo.delete!("h")
>
> then both foo and bar become "ello". How come bar isn't independent of
> foo in this case?
>
> If I then type
>
> foo = foo + "oo"
>
> 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.
I hope this helps
Stefano