K
kieran kirwan
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
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