Hello Mauricio,

Wednesday, October 09, 2002, 10:14:38 PM, you wrote:

>> BT>    13. There is no standard, built-in deep copy in Ruby. One way to
MF> BTW, the list is available in the Wiki too
MF> http://www.rubygarden.org/ruby?ThingsNewcomersShouldKnow
MF> you might edit it if you like.

well, i changed this to text below. but i think it is better described
as "things that newcomers don't want to know" :) TOO MUCH

13) ruby variables holds references to objects and '=' operator copies these references:

a='x'
b=a
a.upcase!
# now both a and b points to string containing 'X'

parameters to methods and closures also passed as references to actual objects. in order to get new, unbounded copy of variable value, you can use "dup" method:

a='x'
b=a.dup

it may be advisable to know whether you modify existing object or
create new one. as a rule of thumb is

1) methods ending with '!' modifies value in place
2) almost all other methods creates new objects
3) 'x+=b', 'x*=b' and other assignment operators is internally translated into 'x=x+b' and so on, so these operators assign to x reference to newly created object

arrays, hashes and other containers also holds references. so, for example

a = []
a[1] = s = 'word'
s.upcase!
puts a[1]  #=> 'WORD'

one notable exception is what KEY (but not value) of hash is copied from original value (using #clone ?)

interesting (and may be undesirable) effect is parameters to some methods which will be BOTH used several times and each copy may be modified: Array.new(Fixnum,Object), Array#fill, Hash.new(Object). These methods will assign the same pointer to several cells in hash/array and then changing value thorough one pointer will be seen in all these cells:

a = []
a.fill('x',0,2)
a[0].upcase!
p a


-- 
Best regards,
 Bulat                            mailto:bulatz / integ.ru