Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
simple newbie question
kieran kirwan
1/26/2006 1:58:00 AM
Hi,
I have a piece of code below in which I;
1.....make a new NumberList object and append two MyNumber objects.
2.....copy the NumberList object and append a further MyNumber object.
However after this both objects are the same.
Any help would be greatly appreciated.
Thanks,
Kieran
---------------------------------------------------
class MyNumber
def initialize(x)
@x=x
end
attr_accessor :x
end
class MyNumberList
def initialize
@nums = Array.new
end
def append(num)
@nums.push(num)
self
end
def sum
sum=0
@nums.each {|s| sum += s.x }
return sum
end
end
zl1=MyNumberList.new; zl1.append(MyNumber.new(10));
zl1.append(MyNumber.new(20))
puts zl1.sum
zl2=zl1; zl2.append(MyNumber.new(40))
puts zl1.sum
puts zl2.sum
--
Posted via
http://www.ruby-...
.
2 Answers
dblack
1/26/2006 2:14:00 AM
0
Eric Jacoboni
1/26/2006 12:26:00 PM
0
kieran kirwan <kieran.kirwan@dto.ie> writes:
> Hi,
> I have a piece of code below in which I;
> 1.....make a new NumberList object and append two MyNumber objects.
> 2.....copy the NumberList object and append a further MyNumber object.
> However after this both objects are the same.
> Any help would be greatly appreciated.
See <
http://www.rubygarden.org/ruby?Make_A_Deep_Copy_Of_An_...
> zl2=zl1;
As said, you doesn't copy the contents of zl1 in zl2: you make zl2 and
zl1 reference the same objet. What you want to do is to copy the
*contents* of zl1 into zl2.
--
Eric Jacoboni, ne il y a 1441718614 secondes
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
simple newbie question
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password