From: Robert Klemme Date: 2013-04-17T23:08:29+09:00 Subject: Re: Delete method also deletes the original variable --bcaec519613b1b61c804da8f0580 Content-Type: text/plain; charset=ISO-8859-1 On Wed, Apr 17, 2013 at 5:51 AM, Vincent Stowbunenko wrote: > Suppose a code is like this: > > array1 = [1,2,3,4,5] > array2 = array1 > array2.delete(1) > > And the result was: > > array2 => [2,3,4,5] > array1 => [2,3,4,5] > > How do I make sure the first array stays original after the modification > of second array? > Adding to what Garthy said: you need to be aware that there is only one Array, not two as your speaking of a "first array" and "second array" indicates. The effect is called "aliasing": two variables reference the same instance. Btw, it happens all the time, for example when invoking methods. http://en.wikipedia.org/wiki/Aliasing_(computing) Another way of preventing changes to an Array is freezing it. That does not automatically freeze the contained objects though! Yet another way is to do the filtering in one step irb(main):001:0> array1 = [1,2,3,4,5] => [1, 2, 3, 4, 5] irb(main):002:0> array2 = array1.reject {|x| x == 1} => [2, 3, 4, 5] irb(main):003:0> array2 = array1[1..-1] => [2, 3, 4, 5] irb(main):004:0> array2 = array1.slice(1..-1) => [2, 3, 4, 5] irb(main):005:0> array1 => [1, 2, 3, 4, 5] Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ --bcaec519613b1b61c804da8f0580 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable



On Wed, Apr 17, 2013 at 5:51 AM, Vincent Stowbunenko <lists@rub= y-forum.com> wrote:
Suppose a code is like this:

array1 =3D [1,2,3,4,5]
array2 =3D array1
array2.delete(1)

And the result was:

array2 =3D> [2,3,4,5]
array1 =3D> [2,3,4,5]

How do I make sure the first array stays original after the modification of second array?

Adding to what Garthy said: you need to be aware that there is only one Ar= ray, not two as your speaking of a "first array" and "second= array" indicates. =A0The effect is called "aliasing": two v= ariables reference the same instance. =A0Btw, it happens all the time, for = example when invoking methods.
http://en.wikipedia.org/wiki/Aliasing_(computing)

Ano= ther way of preventing changes to an Array is freezing it. =A0That does not= automatically freeze the contained objects though!

Yet another way is to do the filtering in one step

irb(main):001:0> array1 =3D [1,2,3,4,5]
= =3D> [1, 2, 3, 4, 5]
irb(main):002:0>= array2 =3D array1.reject {|x| x =3D=3D 1}
= =3D> [2, 3, 4, 5]
irb(main):003:0> array2 =3D array1[1..-1]
=3D> [2, 3, 4, 5]
irb(main):004:0> array2 =3D array1.slice(1..-1)
=3D> [2, 3, 4, 5]
irb(main):005:0> ar= ray1
=3D> [1, 2, 3, 4, 5]

=
Kind regards

robert


<= /div>--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/<= /a>
--bcaec519613b1b61c804da8f0580--