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 <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?