先日解いた問題1[Ruby]
ソースコードはこんな感じだったと記憶している
def append str, other_str
str = str + other_str
puts "append : #{str}"
str
end
def append! str, other_str
str = str.concat(other_str)
puts "append! : #{str}"
str
end
str1 = "Test"
str2 = "Program"
append(str1,str2)
puts "1st : #{str1}"
append!(str1,str2)
puts "2nd : #{str1}"
=begin
実行結果
append : TestProgram
1st : Test
append! : TestProgram
2ed : TestProgram
=end
上記より、「出力された 1st と 2ndの内容が違うのはなぜか」という出題
ポイントはconcat
self << other -> self
concat(other) -> self
self に文字列 other を破壊的に連結します。 other が 0 から 255 のまでの整数である場合は その 1 バイトを末尾に追加します (つまり、整数が示す ASCII コードの文字が追加されます)。
self を返します。
instance method String#<< (Ruby 2.2.0)
破壊的に上書きすると解答したが、「破壊的に連結する」というのが正答のようです