Forum: Ruby simple newbie question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
kieran kirwan (Guest)
on 2006-01-26 03:58
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
unknown (Guest)
on 2006-01-26 04:16
(Received via mailing list)
Hi --

On Thu, 26 Jan 2006, kieran kirwan wrote:

> 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.
[...]
> zl2=zl1

That's why they're the same: by doing this assignment, you're storing
a new reference to the object in zl2.  But it's still the same object.


David

--
David A. Black
removed_email_address@domain.invalid

"Ruby for Rails", from Manning Publications, coming May 1, 2006!
http://www.manning.com/books/black
Eric J. (Guest)
on 2006-01-26 14:28
(Received via mailing list)
kieran kirwan <removed_email_address@domain.invalid> 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...

> 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.
This topic is locked and can not be replied to.