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[-1].concat(“j”)
=> [“a”, “b”, “cjj”, “cjj”]
My expected output is: [“a”, “b”, “c”, “cj”]
Thanks
concat modifies the string:
irb(main):001:0> s = “foo”
“foo”
irb(main):002:0> s.concat(“x”)
“foox”
irb(main):003:0> s
“foox”
If you want to get the concatenation without modifying the string, use
“+” instead.
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
John W Higgins wrote in post #1108782:
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”]
Perfect! Thanks for the wright directions.