Why are << and += building a different string?

时间:2015-07-28 16:30:06

标签: ruby string

I wrote a function that iterates over a string character by character, pulling values from a hash using each character as a key. The values in the hash were used to build a new string:

acc = ''
str.each_char do |c|
  acc << somehash[c]
end

If the string was longer than one, the first character would be looked up and its hash value be interpolated several times in the built string, which was not what I wanted. I rewrote the line with << as

acc += somehash[c]

and it behaved correctly. Why am I getting different behavior from << and +=?

NOTE: I'm no longer getting this behavior, and my unit tests are passing. I'm not sure why since I didn't touch the logic in the loop.

1 个答案:

答案 0 :(得分:5)

s1 << s2 appends the string s2 to s1, whereas s1 += s2, which expands to s1 = s1 + s2, creates a new object which becomes the new value of the variable s1.

Consider the following.

s1 = "ab"
s1.object_id #=> 70117580969460 
s2 = "cd"

s1 << s2     #=> "abcd" 
s1           #=> "abcd" 
s1.object_id #=> 70117580969460 

Compare that with:

s1 = "ab"
s1.object_id #=> 70117576935280 
s2 = "cd"

s1 += s2     #=> s1 = s1 + s2 => "abcd" 
s1           #=> "abcd" 
s1.object_id #=> 70117576870900