From: John W Higgins Date: 2013-05-13T22:47:18+09:00 Subject: Re: Unexpected output from Array#<< method. --001a11c34b662f0d6204dc99c1ac Content-Type: text/plain; charset=ISO-8859-1 a[-1] is the object - not the value of the object - therefore a[-1].concat("j") created ["a", "b", "cj"] in your array on the 2nd line. Then you added another "j" and then pushed that value again onto the stack. Now to really make you think look at this irb(main):001:0> a = ["a"] => ["a"] irb(main):002:0> a[0].concat("b") => "ab" irb(main):003:0> a => ["ab"] irb(main):004:0> a << a[0] => ["ab", "ab"] irb(main):005:0> a[0].concat("c") => "abc" irb(main):006:0> a => ["abc", "abc"] You are dealing with references not values here. If you want values then use.dup irb(main):007:0> a = ["a"] => ["a"] irb(main):008:0> a[0].dup.concat("b") => "ab" irb(main):009:0> a => ["a"] irb(main):010:0> a << a[0].dup => ["a", "a"] irb(main):011:0> a[0].concat("c") => "ac" irb(main):012:0> a => ["ac", "a"] John On Mon, May 13, 2013 at 6:04 AM, Love U Ruby wrote: > I was writing a code,and doing so I got some unexpected result. Can > anyone point me by saying where I did wrong? > > > irb(main):001:0> a=["a","b","c"] > => ["a", "b", "c"] > irb(main):002:0> a[-1].concat("j") > => "cj" > irb(main):003:0> a< => ["a", "b", "cjj", "cjj"] > > My expected output is: ["a", "b", "c", "cjj"] > > Thanks > > -- > Posted via http://www.ruby-forum.com/. > > --001a11c34b662f0d6204dc99c1ac Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
a[-1] is the object - not the value of the = object - therefore a[-1].concat("j") created ["a", &quo= t;b", "cj"] in your array on the 2nd line. Then you added an= other "j" and then pushed that value again onto the stack.

Now to really make you think look at this

irb(main):001:0&= gt; a =3D ["a"]
=3D> ["a"]
irb(main):002:0>= a[0].concat("b")
=3D> "ab"
irb(main):003:0>= ; a
=3D> ["ab"]
irb(main):004:0> a << a[0]
=3D> = ["ab", "ab"]
irb(main):005:0> a[0].concat("c= ")
=3D> "abc"
irb(main):006:0> a
=3D> [&qu= ot;abc", "abc"]

You are dealing with references not values here. If you want valu= es then use.dup

irb(main):007:0> a =3D ["a"]
=3D>= ["a"]
irb(main):008:0> a[0].dup.concat("b")
=3D> "ab"
irb(main):009:0> a
=3D> ["a"]
irb(main):010:0> a = << a[0].dup
=3D> ["a", "a"]
irb(main):01= 1:0> a[0].concat("c")
=3D> "ac"
irb(main):0= 12:0> a
=3D> ["ac", "a"]


John


On Mon, May 13, 2= 013 at 6:04 AM, Love U Ruby <lists@ruby-forum.com> wrote:=
I was writing a code,and doing so I got some= unexpected result. Can
anyone point me by saying where I did wrong?


irb(main):001:0> a=3D["a","b","c"]
=3D> ["a", "b", "c"]
irb(main):002:0> a[-1].concat("j")
=3D> "cj"
irb(main):003:0> a<<a[-1].concat("j")
=3D> ["a", "b", "cjj", "cjj"]
My expected output is: ["a", "b", "c", "= cjj"]

Thanks

--
Posted via http://= www.ruby-forum.com/.


--001a11c34b662f0d6204dc99c1ac--